Java How use Spring Autowired in SystemInitializer class

血红的双手。 提交于 2019-12-24 06:44:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!