第一次使用quartz定时任务,遇到的问题挺多的,这就是其中一个;
我在使用spring整合quartz时,在逻辑代码中以为所有逻辑都写好了,在运行时,信息数据为空,查了许多资料才发现,在quartz的逻辑代码中无法使用Spring的注入,所以只能手动注入
注入类:
package org.springblade.modules.quartz.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Locale;
/**
* @Author WuJunFei
* @Datetime 2021/6/8 0008 上午 10:12
* @Description
*/
@Component
public class SpringContextJobUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
@SuppressWarnings("static-access")
public void setApplicationContext(ApplicationContext contex) throws BeansException {
this.context = contex;
}
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
public static String getMessage(String key) {
return context.getMessage(key, null, Locale.getDefault());
}
}
在quartz逻辑代码类中,自定义注入的使用:
package org.springblade.modules.quartz.util;
/**
* @Author WuJunFei
* @Datetime 2021/6/4 0004 下午 21:16
* @Description 子任务逻辑代码
*/
@Component
public class WorkJobLogic implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) {
//解析:将需要注入的类手动注入,自定义类名首字母小写,然后强转成注入的类,此时就可以调用类中的方法
//以下以:注入 WorkJobServiceImpl,和 DeviceMapper 为例子,具体按自己所需注入
//自定义注入子任务
WorkJobServiceImpl workJobService = (WorkJobServiceImpl) SpringContextJobUtil.getBean("workJobServiceImpl");
//通过自定义工具类,将bean注入(注意:在quartz执行时,quartz会将bean初始化,而不是spring的初始化,所以spring的初始化没用)
DeviceMapper deviceMappers = (DeviceMapper) SpringContextJobUtil.getBean("deviceMapper");
}
}