spring+quartz 实现定时任务三

其实,上面2篇都已经可以完成所有客户的需求,在这一篇,记录实现过程遇见一个很奇怪的问题.

那就是spring的自动加载

在真正的task里面,难免需要完成对数据库的操作,这样就需要自动注入service.

但是很奇怪,无论如何,无法注入,折腾了很久,service都是null.

于是采用迂回的方式完成bean的注入.

1. 在spring配置文件里面定义一个获取上下文的bean

<bean id ="getContext" class="com.aw.task.ApplicationContextHelper"></bean>

具体代码:

public class ApplicationContextHelper implements ApplicationContextAware  
{  
    private static ApplicationContext context;  
  
    @Override  
    public void setApplicationContext(ApplicationContext contex) throws BeansException  
    {  
        ApplicationContextHelper.context = contex;  
    }  
  
    public static ApplicationContext getContext()  
    {  
        return context;  
    }  
  
}  

2. 在真正实现的task里面,首先定义

private SellerMapper sellerMapper;

ApplicationContext context = ApplicationContextHelper.getContext();
sellerMapper = (SellerMapper)context.getBean("sellerMapper"); 

这样才能获取到mapper的bean.

在非task的类里面,service的bean也可以直接获取到,但是在上面的代码里面,只能获取到mapper类,实在找不到什么情况了.

如果有大神知道的还请指导下.

原文地址:https://www.cnblogs.com/raspberry/p/5534741.html