不要手动创建代理,使用Spring AOP创建日志代理。
创建一个简单的方面:
@Aspect
public class LoggingAspect{
private static final Logger log = Logger.getLogger(LoggingAspect.class);
@Pointcut("execution(* *.*(..))")
public void methodExecution(){
}
@Before("methodExecution()")
public void logBeforeMethod(final JoinPoint joinPoint){
log.trace("Entering method " + joinPoint.getSignature() + " with args "
+ Arrays.toString(joinPoint.getArgs()));
}
}
现在在 Spring 中连接方面:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="aspects.LoggingAspect" />
<aop:aspectj-autoproxy />
</beans>
现在,您所有的 Spring Bean 都将成为代理,并且它们的所有方法执行(至少由接口支持的方法执行)都将被记录下来。
顺便说一句: Ramnivas Laddad在AspectJ in Action的免费第 10 章中介绍了跟踪方面