SpringBoot框架中Quartz定时任务无法注入Service实例解决方法

一、问题

在Quartz定时任务中用@Autowired注入Service对象时失败,报错NullPointerException

二、原因

这是spring的一个Bug ,需要手动去配置一个类,主动获取实例,在定时任务中(继承TimerTask类),@Autowired 是失效的,无法注入

三、解决方法

1、添加一个工具类

@Component
public class ApplicationContextUtil implements ApplicationContextAware {
    
    

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
    
    
        return applicationContext;
    }


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

    }


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

2、在servcie的实现类注解添加名字,以便获取

@Service("myService")
public class StopServiceImpl implements StopService

3、在Quartz定时任务中实例化

StopService stopService = (StopService) ApplicationContextUtil.getBean("myService");

猜你喜欢

转载自blog.csdn.net/LCHONSEONE/article/details/128997448