springboot 整合quartz 出现的spring Bean无法注入

160 阅读1分钟
本次开发过程中需要用到定时任务,评估之后决定使用quartz框架,但在过程中发现抛出springbean无法注入的问题,解决方法如下:

自定义类,继承QuartzInitializerListener

package com.gjrmyy.examforcom.service.SchedulerJob;

import org.quartz.SchedulerException;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
@Component
public class QuartzServletContextListener extends QuartzInitializerListener {
    public static final String MY_CONTEXT_NAME = "servletContext";
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        super.contextDestroyed(sce);
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        super.contextInitialized(sce);
        ServletContext servletContext = sce.getServletContext();
        StdSchedulerFactory factory = (StdSchedulerFactory) servletContext
                .getAttribute(QuartzInitializerListener.QUARTZ_FACTORY_KEY);
        try {
            factory.getScheduler().getContext()
                    .put(QuartzServletContextListener.MY_CONTEXT_NAME, servletContext);
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
在job类中的需要用到其它bean,不能使用@Autowired进行注入,通过实例获得,如下:

@Override public void execute(JobExecutionContext jobContext) { 
ServletContext context = null;
try {
context = (ServletContext) jobContext.getScheduler().getContext() .get(QuartzServletContextListener.MY_CONTEXT_NAME);
} 
catch (SchedulerException e1) { 
e1.printStackTrace(); 
} 
WebApplicationContext cxt = (WebApplicationContext) context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); 
//就可以获取spring中的bean了 
HotelService hotelService = (HotelService) cxt.getBean("hotelServiceImpl");
}