Java Spring AOP: Using CustomizableTraceInterceptor with JavaConfig @EnableAspectJAutoProxy, not XML <aop:advisor>

Abdull picture Abdull · Nov 1, 2012 · Viewed 11.6k times · Source

Spring AOP has a method-level tracer called CustomizableTraceInterceptor. Using Spring's XML configuration approach, one would set up this tracer like so:

<bean id="customizableTraceInterceptor" class="
  org.springframework.aop.interceptor.CustomizableTraceInterceptor">
  <property name="enterMessage" value="Entering $[methodName]($[arguments])"/>
  <property name="exitMessage" value="Leaving $[methodName](): $[returnValue]"/>
</bean>

<aop:config>
  <aop:advisor advice-ref="customizableTraceInterceptor"
    pointcut="execution(public * org.springframework.data.jpa.repository.JpaRepository+.*(..))"/>
</aop:config>

I would like to set up above configuration using Spring's JavaConfig style (i.e. taking advantage of Java annotations, especially @EnableAspectJAutoProxy for activating AspectJ in JavaConfig).

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "some.package" })
@ComponentScan(basePackages = { "some.package2", "some.package3" })
@EnableAspectJAutoProxy
public class FacebookDomainConfiguration {

    @Bean someBean() {
    ...
    }
...
}

What is the @EnableAspectJAutoProxy-style equivalent for <aop:advisor advice-ref="customizableTraceInterceptor" ...>?

Answer

Adrien Colson picture Adrien Colson · Feb 21, 2014

I do it this way :

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class TraceLoggerConfig {

    @Bean
    public CustomizableTraceInterceptor customizableTraceInterceptor() {
        CustomizableTraceInterceptor customizableTraceInterceptor = new CustomizableTraceInterceptor();
        customizableTraceInterceptor.setUseDynamicLogger(true);
        customizableTraceInterceptor.setEnterMessage("Entering $[methodName]($[arguments])");
        customizableTraceInterceptor.setExitMessage("Leaving  $[methodName](), returned $[returnValue]");
        return customizableTraceInterceptor;
    }

    @Bean
    public Advisor jpaRepositoryAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(public * org.springframework.data.jpa.repository.JpaRepository+.*(..))");
        return new DefaultPointcutAdvisor(pointcut, customizableTraceInterceptor());
    }

}