Tuesday, 10 September 2013

Spring AOP Controller Executing twice

Spring AOP Controller Executing twice

My applicationContext is as follows
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..">
<mvc:annotation-driven/>
<task:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.abc">
<context:include-filter type="aspectj"
expression="com.abc.aspects.LogControllerAspect"/>
</context:component-scan>
<context:annotation-config />
</beans>
Have 2 Aspect Java classes, LogControllerAspect (for logging all the calls
to Spring Controllers) and LogDAOAspect (for logging all the calls to DB).
@Aspect
@Service
public class LogDAOAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Around("execution(* com.*.*DAOImpl.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
String methodId =
joinPoint.getTarget().getClass().getSimpleName()+" :
"+joinPoint.getSignature().getName() + " : " +
((joinPoint.getArgs()==null||joinPoint.getArgs().length<1)?"":(Arrays.toString(joinPoint.getArgs())));
Object returnVal = null;
StopWatch sw = new StopWatch(methodId);
try {
sw.start();
returnVal= joinPoint.proceed(joinPoint.getArgs());
sw.stop();
} catch (Throwable e) {
logger.error(methodId+"\n"+e);
throw e;
}
logger.debug(methodId + ":" +sw.getTotalTimeMillis());
return returnVal;
}
}
@Aspect
public class LogControllerAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Around("execution(* com.*.*Controller.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
String methodId =
joinPoint.getTarget().getClass().getSimpleName()+" :
"+joinPoint.getSignature().getName() + " : " +
((joinPoint.getArgs()==null||joinPoint.getArgs().length<1)?"":(Arrays.toString(joinPoint.getArgs())));
Object returnVal = null;
StopWatch sw = new StopWatch(methodId);
try {
sw.start();
returnVal= joinPoint.proceed(joinPoint.getArgs());
sw.stop();
} catch (Throwable e) {
logger.error(methodId+"\n"+e);
throw e;
}
logger.debug(methodId + ":" +sw.getTotalTimeMillis());
return returnVal;
}
}
LogDAOAspect is fine, but LogControllerAspect is logging twice (logAround
method is executing twice) when I request some page. I can understand that
that aspect is getting proxied twice, but am not sure how to avoid this.
Help appreciated.

No comments:

Post a Comment