Spring AOP有一个限制,它对嵌套方法调用不起作用。究其原因,是因为Spring aop是作用在spring beans上,而不是作用于实际的类的实例。举例来说:
比如我按如下方法配置了一个aspect,
<bean
class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
<bean id="positionAspect"
class="com.MyPositionUpdateAspect"/>
在这个aspect里(使用aspectj的语法支持),我配置了我的pointcut,意思是对MyTradeProcessor的所有方法调用(正常返回的)进行拦截。
package com;
@Aspect
public class MyPositionUpdateAspect {
@AfterReturning(value = "execution(* com.MyTradeProcessor.*(..))", returning = "retTrade")
public void updatePosition(JoinPoint joinPoint, Object retTrade) throws Throwable {
// my business logic
}
}
下面是MyTradeProcessor类的大致框架:
public class MyTradeProcessor {
public ITrade amend(ITrade inputTrade) throws TradeBookingException {
if (isAmendForTemp)
return newTrade(inputTrade);
}
// other logic
}
public ITrade newTrade(ITrade inputTrade) throws TradeBookingException {
// newTrade logic
}
}
还有一种解决办法是利用aspectj weaving。大致的配置如下,详细的说明可以参考http://stackoverflow.com/questions/5780757/spring-aop-logging-and-nested-methods。
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver options="-Xset:weaveJavaxPackages=true -verbose -showWeaveInfo -debug">
<include within="*"/>
</weaver>
<aspects>
<!-- weave in just this aspect -->
<aspect name="your.logger.impl.LoggingImpl"/>
</aspects>
</aspectj>
This implies weaving in all your files ('within=*', modify as you wish) with the aspect/s specified. On load time you should see verbose information on weaving of classes.
<context:load-time-weaver aspectj-weaving="autodetect"
weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>

本文探讨了Spring AOP在处理嵌套方法调用时的局限性,并提供了解决方案,包括利用AspectJ的特殊配置来实现对嵌套方法的拦截与监控。
3034

被折叠的 条评论
为什么被折叠?



