SpringBoot集成Quartz动态添加定时任务时Autowired为null的另一种解决方法

在SpringBoot项目中集成Quartz实现动态添加定时任务时,遇到Job实现类中@Autowired注解的DAO为null的问题。通过搜索资料尝试多种方案未果,最后通过创建SpringContextUtil工具类,利用ApplicationContext.getBean方法手动注入,成功解决了这个问题。

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

最近在做项目时,因为业务需要,得动态添加定时任务,在网上找了一些资料之后顺利集成。但是发现在Job实现类里Autowired自动注入dao时,dao为null,导致无法对数据库进行修改。遂又去网上搜索解决方案。后来找到两种,均未能成功。百思不得其解时,灵机一动,想起在别的项目中看过用ApplicationContext.getBean方法可以注入,试了一下,果然可行。

写一个SpringContextUtil工具类

@Component
public class SpringContextUtils implements ApplicationContextAware {
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws         BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	public static <T> T getBean(Class<T> cls) {
        return applicationContext.getBe
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值