解决Spring定时任务中无法注入service问题

场景:今天在做定时发送邮件时,需要访问数据库操作,代码写好后,发现service一直为null,service没有注入成功。以下是错误信息Caused by: org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'autoSendMail' on target class [class com.dcb1.barge.util.AutoMessageOfMultipleBerthing] failed; nested exception is java.lang.NullPointerException。

原因分析:由于定时任务的优先级高于Spring的自动注入,所以我们得其他方法注入service。

解决方法:创建一个工具类实现ApplicationContextAware接口

public class xxxUtil implements ApplicationContextAware {
    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return context;
    }
    public static Object getBeans(String name) {
        return getApplicationContext().getBean(name);
    }
}  

在定时任务中引用getBeans方法,通过名称得到service实例。

通过此方法即可解决在定时任务中无法注入属性问题。

本文参考自:https://www.cnblogs.com/bobguo/p/9441995.html

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值