在使用spring整合quartz时,工作类中无法使用Spring的注入,需要手动注入

本文介绍了在Spring集成Quartz时如何解决逻辑代码中无法使用Spring注入的问题,分享了SpringContextJobUtil类的实现和如何在Job类中手动注入Bean的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一次使用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");
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈极客小飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值