Java如何在SystemInitializer类中使用Spring Autowired
我有一个Spring MVC
的Java项目.
我的应用程序初始化后,我已经需要启动TimerTasks,因此我实现了WebApplicationInitializer
接口,并将其称为SystemInitializer
.在该类内部,我有一个@Autowired
属性,该@Autowired
属性是一个DAO
类.
我需要它是因为我想根据数据库中的记录执行一些任务.但是该Autowired属性永远不会为空.
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");
}
}
您不能在WebApplicationInitializer
内使用@Autowired
.
您的Bean尚未准备好(尚未扫描)要注入.您的应用程序当时不知道DomainResearchDao
是什么.
Your Beans are not ready (not scanned yet) to be injected. Your Application has no idea what DomainResearchDao
is at that moment.
只有在初始化应用程序并创建所有(单个)实例(@Component
,@Service
等)之后,Spring才能自动装配bean.
Spring can autowire beans only after your application is initialized and all (singletone) instances (@Component
, @Service
etc.) are created.
如果要在启动应用程序后执行一些工作,请使用Spring Event进行此操作:
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.