Sunday, March 20, 2011

Named pointcut expression

Sometimes it happens that we may need same pointcut at multiple places. But since pointcut expressions are lengthy, it will be good if instead of repeating we can give a logical name to that pointcut and refer to it by logical name.

So for this we have to first create pointcut config :

package com.xxxx;
//
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class PointcutConfig {

@Pointcut("execution(public * service.*.*(..))") //This is a pointcut expression
public void serviceComponents() {} //This is a name given to the pointcut expression

@Pointcut("execution(* apply*(..))")
public void applyMethods() {}

}



Note that we @Aspect and @Pointcut annotations above.


When we write our own aspect we can simply refer to these method names in pointcut-config now:


import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

@Before("com.xxxx.PointcutConfig.applyMethods()")
public void log(JoinPoint joinPoint) {
System.out.println("log advice executed for method : "+joinPoint.getSignature().getName());
}

@Before("com.xxxx.PointcutConfig.serviceComponents()")
public void timeLog(JoinPoint joinPoint) {
System.out.println("request for method : "+joinPoint.getSignature().getName()+" occurred at "+new Date());
}
}


In the config file, we have to define both beans:


<aop:aspectj-autoproxy />

<bean id="pointcutConfig" class="ex4.PointcutConfig" />

<bean id="loggingAspect" class="ex4.LoggingAspect" />

<bean class="service.OrderServiceImpl" />

<bean class="service.CustomerServiceImpl" />

No comments:

Post a Comment

Chitika