39
votes

I am trying to set up Spring AOP without any XML. I'd like to enable <aop:aspectj-autoproxy> in a class which is annotated with @Configuration.

This is the way it would be defined in an XML-file:

<aop:aspectj-autoproxy>
<aop:include name="msgHandlingAspect" />
</aop:aspectj-autoproxy>

I tried to annotate my class with @Configuration and @EnableAspectJAutoProxy but nothing happened.

2

2 Answers

48
votes

Did you create an aspect bean in the same @Configuration class? Here's what the docs suggest:

 @Configuration
 @EnableAspectJAutoProxy
 public class AppConfig {
     @Bean
     public FooService fooService() {
         return new FooService();
     }

     @Bean // the Aspect itself must also be a Bean
     public MyAspect myAspect() {
         return new MyAspect();
     }
 }
2
votes

I used the accepted answer solution but I had unexpected problems and never understand untill to add this parameter to configuration.

@EnableAspectJAutoProxy(proxyTargetClass = true)

If you use annotation into @Controller you'll need to configure in this way

remember if you have java 8 you need to use a version of AspectJ greater than 1.8.X

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

    @Bean
    public AccessLoggerAspect accessLoggerAspect() {
        return new AccessLoggerAspect();
    }

}