0
我的ApplicationContext需要如下Spring AOP的控制器執行兩次
<?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>
有2個看點Java類,LogControllerAspect(用於記錄所有的呼叫到Spring控制器)和LogDAOAspect(用於記錄所有來電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是好的,但LogControllerAspect正在記錄兩次(logAround方法正在執行兩次)時,我要求的一些頁。我可以理解,該方面代表了兩次,但不知道如何避免這種情況。幫助讚賞。
你確定控制器方法運行一次嗎?也許有兩個方法調用。 – erencan
該方法只被調用一次(我設置了一個斷點,它只打了一次) –
你應該檢查COntroller軟件包'* com。*。* Controller。*(..) – erencan