Tuesday, October 24, 2006

crazy for aspects

I stayed up too late into the evening trying to learn aspectJ. I think we should consider its use more often. It makes things like logging simple.
Note that it requires that you modify your eclipse environment to have the aspectj compiler. Or, download the eclipse tools here:
download aspectj developer tools

Then watch this quick demo:
demo of aspectj tools

What I like most about the tool, is that it shows you where your advice will be applied!

** Note, if you are using BEAWorkshop, for some strange reason BEA doesn't include the PDE plugins for eclipse, and although the tool(ajdt) will be installed, it didn't work for me, until I manually added this plugin via the eclipse software update function.

The real time consuming thing is to figure out how to define pointcuts (where your code will run), and the aspectj syntax. Hopefully my samples will make it easy.

Here's some sample aspects I wrote:

public aspect ServiceLayerAspect {
/**
* intercept executiong of methods begining w/ pkg name com.service, ending with name service
* and any method
*/
pointcut methodsEndingWithNameService():
//any pkg or subpackage of service
within(pkg.pkg.pkg..*)
// && execution(public * pkg.pkg.pkg.*.*Service.*(..))
//classname ends in Service
&& execution(public * com..*Service.*(..))
&& !execution(public * get*())
&& !execution(public void set*(..))
;

before(): methodsEndingWithNameService() {
Logger log = Logger.getLogger(thisJoinPointStaticPart.getSignature().getDeclaringType().getName());

log.debug("before service method "+thisJoinPointStaticPart.getSignature().getName());
}
}




public aspect DomainLayerBusLogicLogger {
/**
* intercept executiong of methods begining w/ pkg name com.service, ending with name service
* and any method
*/
pointcut methodsNotGetSet():
// call(public * get*(..));
// &&
within(pkg.pkg.domain..*)
&& execution(public * *(..))
&& !execution(public * get*())
&& !execution(public void set*(..))
;

before(): methodsNotGetSet() {
Logger log = Logger.getLogger(thisJoinPointStaticPart.getSignature().getDeclaringType());
log.debug("bus domin method:"+thisJoinPointStaticPart.getSignature().getName());
}
}


public aspect StrutsLoggingAspect {
/**
* find methods that return an ActionForward, and extend DispatchAction
*/
pointcut dispatchingActionForwards():
execution(public org.apache.struts.action.ActionForward
org.apache.struts.actions.DispatchAction+.*(..));

before(): dispatchingActionForwards() {
Logger log = Logger.getLogger(thisJoinPoint.getTarget().getClass());

log.debug("Web action start:"+thisJoinPointStaticPart.getSignature().getName());
}

No comments: