I have the following spring configuration:
<context:component-scan base-package="uk.co.mysite.googlecontactsync.aop"/> <bean name="simpleEmailSender" class="uk.co.mysite.util.email.simple.SimpleEmailSenderImplementation"/> <aop:aspectj-autoproxy/>
Then I have an aspect:
@Aspect public class SyncLoggingAspect { @Autowired private SimpleEmailSender simpleEmailSender @AfterReturning(value="execution(* uk.co.mysite.datasync.polling.Poller+.doPoll())", returning="pusher") public void afterPoll(Pusher pusher) { simpleEmailSender.send(new PusherEmail(pusher)); } }
This aspect works (I can hit a breakpoint on afterPoll) but simpleEmailSender is null. Unfortunately I cannot find clear documentation on why this is. (For the record, my simpleEmailSender bean exists and is correctly wired into other classes) The following things confuse me:
Obviously you can tell I don't have an understanding of how things should be working from the ground up.
The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.
An aspect can be created in spring boot with help of annotations @Aspect annotation and registering with bean container with @Component annotation. Inside the aspect class, we can create advices as required. For example, below class applies around advice on methods inside all classes in package com.
By default, the @Autowired annotation implies that the dependency is required. This means an exception will be thrown when a dependency is not resolved. You can override that default behavior using the (required=false) option with @Autowired .
When @Autowired doesn't work. There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With