Spring autowired bean for @Aspect aspect is null Spring autowired bean for @Aspect aspect is null spring spring

Spring autowired bean for @Aspect aspect is null


The aspect is a singleton object and is created outside the Spring container. A solution with XML configuration is to use Spring's factory method to retrieve the aspect.

<bean id="syncLoggingAspect" class="uk.co.demo.SyncLoggingAspect"      factory-method="aspectOf" />

With this configuration the aspect will be treated as any other Spring bean and the autowiring will work as normal.

You have to use the factory-method also on Enum objects and other objects without a constructor or objects that are created outside the Spring container.


Another option is to add @Configurable to your aspect class instead of messing around with XML.


For Spring Boot to use @Autowired with AspectJ I have found the following method.In configuration class add your aspect:

@Configuration@ComponentScan("com.kirillch.eqrul")public class AspectConfig {    @Bean    public EmailAspect theAspect() {        EmailAspect aspect = Aspects.aspectOf(EmailAspect.class);        return aspect;    }}

Then you can successfully autowire your services in your aspect class:

@Aspectpublic class EmailAspect {    @Autowired    EmailService emailService;