场景:今天在做定时发送邮件时,需要访问数据库操作,代码写好后,发现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实例。
通过此方法即可解决在定时任务中无法注入属性问题。