14

I am using Spring Boot, and I would like to use AspectJ with it.

The following works (of course):

@Aspect
@Component
public class RequestMappingAspect {

    @Before("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void advice(JoinPoint joinPoint) {
        ...
    }
}

However, if @Component is removed and @EnableAspectJAutoProxy is added, the following does not work.

@SpringBootApplication
@EnableSwagger2
@EnableAspectJAutoProxy
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

How to enable AspectJ auto proxy correctly?

Dante May Code
  • 11,177
  • 9
  • 49
  • 81
  • With `@EnableAspectJAutoProxy` you do not use AspectJ, but proxy-based Spring AOP. But probably that is what you want anyway. – kriegaex Jan 23 '17 at 11:02
  • 2
    Ofcourse it won't work... I you remove `@Component` no instance of the aspect will be created, hence no aspects available so nothing to use. You need both `@Component` and `@Aspect` to make it work (or define the aspect as a `@Bean` method). Either way an instance of the aspect has to be there to make it work. – M. Deinum Jan 23 '17 at 12:29

2 Answers2

6

Wondering about the same thing, we ended up doing something similar to this:

@EnableAspectJAutoProxy(proxyTargetClass = true)
@Configuration("Main applicationContext")
@ComponentScan(
    basePackages = {"com.where.ever"},
    excludeFilters = {@ComponentScan.Filter(Aspect.class)})
public class ApplicationConfiguration {
    @Bean(autowire = Autowire.BY_TYPE)
    public SomeAspect someAspect() {
        return Aspects.aspectOf(SomeAspect.class);
    }
    ...
    ...
}

This enabled us to just add the @Aspect-annotation on the aspects, which also wired them correctly. Might be that this was a pointless reply, however, it explains how we solved the issue - and not the actual solution to the problem. Let me know if you want this to be deleted.

vegaasen
  • 1,022
  • 7
  • 16
  • There is nothing automatic about this... The aspect is created with an `@Bean` method so if you add a new aspect you need to add another method. – M. Deinum Jan 23 '17 at 12:30
  • 1
    i don't understand why this is the accepted anwser. As M. Deinum says, spring aop can only be applied to beans that are managed by a Spring container. So its normal it not work if you remove @component from your aspect definition. – soung Aug 07 '20 at 12:57
6

You need both @EnableAspectJAutoProxy for the spring configuration and combination of @Aspect / @Component annotations

@EnableAspectJAutoProxy does the same thing as xml based <aop:aspectj-autoproxy>

Kalpesh Soni
  • 6,879
  • 2
  • 56
  • 59