Spring Task中的定时任务无法注入service的解决办法

时间:2018-08-08 22:03:16   收藏:0   阅读:1905

1、问题

因一个项目(使用的是Spring+SpringMVC+hibernate框架)需要在spring task定时任务中调用数据库操作,在使用 @Autowired注入service时后台报错,导致系统不能访问。

2、代码

定时任务的代码如下:

@Component
public class TaskJob {
    
    Logger logger = Logger.getLogger(TaskJob.class);
    
    @Autowired
    private TempService tempService ;
    
    @Scheduled(cron = "* * /1 * * ?")
    public void getDoorToken() {
      //定时执行代码,需要
        ...数据库操作...
      
    }

3、原因分析  

由于定时 @Scheduled的执行优先级高于@Autowired注入,因此我们不能通过@Autowired注入service。

4、解决办法

在定时任务中通过在ApplicationContext中按名称查找service的实例,以便执行后续数据库操作。

4.1 定时任务中代码示例:TempService tempService = (TempService)ApplicationContextUtil.getBean("tempService");
4.2 在ApplicationContext中查找service代码示例:

关键是要实现 ApplicationContextAware,同时需要在Spring中注入

@Component

public class ApplicationContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    ......其他代码......
}      

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!