Java如何在SystemInitializer类中使用Spring Autowired [英] Java How use Spring Autowired in SystemInitializer class

查看:122
本文介绍了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.

这篇关于Java如何在SystemInitializer类中使用Spring Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆