项目场景:
项目场景:在定时任务具体任务代码中,注入Service层Bean,操作数据库,注入失败,发生NPE
问题描述
无法在具体任务代码中,注入Service服务,ServiceBean为null
方式一:加入一行代码在execute
// 方式二 方式二有些人可以 我失效
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
方式一对我失效,用的是方式二解决
解决方案:
加入quartz监听类
package com.jqmkj.ulp.listener;
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;
/**
* @author nzh
* @date 2022/8/23 17:14
*/
@Component
public class QuartzServletContextListener extends QuartzInitializerListener {
public static final String MY_CONTEXT_NAME = "servletContext";
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
super.contextDestroyed(sce);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
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实现类中添加代码
package com.jqmkj.ulp.utils;
/**
* @author nzh
* @date 2022/8/19 8:11
*/
import cn.hutool.core.date.DateUtil;
import com.jqmkj.ulp.listener.QuartzServletContextListener;
import com.jqmkj.ulp.service.IUlpDataService;
import lombok.SneakyThrows;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.SchedulerException;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.ServletContext;
public class RealTimeJob implements Job{
// @Autowired
// IUlpDataService dataService;
@SneakyThrows
@Override
public void execute(JobExecutionContext jobContext) {
// 方式一 方式一有些人可以 我失效
// SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
// 方式二
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);
//要注入的Service服务 通过getBean去拿
IUlpDataService dataService = (IUlpDataService) cxt.getBean("ulpDataServiceImpl");
// UlpDataVO ulpDataVO = dataService.getActualTimeInfo(UlpYukeConsts.TOPO_ID);
// UlpDataPO dataPO = CommonHelper.exchangePOJO(ulpDataVO, UlpDataPO.class);
// dataService.save(dataPO);
System.out.println("现在的时间是 : " + DateUtil.date());
}
}
亲测有效,具体原因以后会了再来记录