zoukankan      html  css  js  c++  java
  • Springboot 定时任务,service层无法注入问题详细解决

    开发一个微信小程序后台,建立websocket 长连接,需要后台开启定时任务,

    定时任务定时查库,相应前台

    但是具体执行过程中一直在报空指针错误,最后定位到service 为空,无法调用其相关的方法导致的

    于是我尝试不用@Autowired 注入实例,自己new ,但是还是失败了,报空指针

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

    解决方案如下:

    1.首先添加一个工具类,就是application

    应注意,同样需要注入添加 @Compent注解

    package com.cskaoyan.carparking.utils;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    
    /**
     * @Auther: YangTao
     * @Date: 2019/2/21 0021
     * 配置类,解决定时任务无法注入的问题
     */
    @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的实现类注解添加名字,以便我们获取

    3.我们在需要的定时任务类中获取service实例就可以使用了

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

      

  • 相关阅读:
    leetcode-832-Flipping an Image
    leetcode-830-Positions of Large Groups
    leetcode-824-Goat Latin(字符串的处理)
    leetcode-821-Shortest Distance to a Character
    leetcode-819-Most Common Word(词频统计)
    HDU 4729 An Easy Problem for Elfness(树链剖分边权+二分)
    python爬虫(1)——正则表达式
    利用MySQL之federated引擎实现DBLink功能
    HTTPS原理及流程
    NIO、多路复用的终极奥义
  • 原文地址:https://www.cnblogs.com/doudou2018/p/10416043.html
Copyright © 2011-2022 走看看