问题
I have a Java Project with Spring MVC
.
I need to start TimerTasks already after my application is initialized, so I implemented the WebApplicationInitializer
Interface and I call it SystemInitializer
. Inside that class I have a @Autowired
property, that @Autowired
property is a DAO
class.
I need it cause I want to execute some tasks based in recordings from my data base. But that Autowired property is ever null.
public class SystemInitializer implements WebApplicationInitializer {
@Autowired
private DomainResearchDao domainResearchDao;
@Override
public void run() {
if (this.domainResearchDao != null) {
System.out.println("OK");
}
// always here
else{
System.out.println("NO OK");
}
}
回答1:
You can not use @Autowired
inside of WebApplicationInitializer
.
Your Beans are not ready (not scanned yet) to be injected. Your Application has no idea what DomainResearchDao
is at that moment.
Spring can autowire beans only after your application is initialized and all (singletone) instances (@Component
, @Service
etc.) are created.
If you want to do some job after your application is started, use Spring Event for doing this:
@Component
public class DoOnStart{
@Autowired
private IYourService service;
@EventListener
public void handleContextRefresh(ContextRefreshedEvent e) {
// your CODE
}
}
Just implement this class, no need to autowire it.
来源:https://stackoverflow.com/questions/37503372/java-how-use-spring-autowired-in-systeminitializer-class