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");
    

      

  • 相关阅读:
    Css3 常见鼠标滑过效果集合
    HTML5 Media事件
    HTML 5 Audio/Video DOM buffered 属性
    Cocos2d-x 3.X 事件分发机制
    在 WPF 程序中使用 MVVM 模式
    Windows Phone 版 Cocos2d-x 程序的结构
    转载:Cocos2D-x 游戏接入 Windows 设备所需做的六件事
    使用 Cocos2d-x 3.1.1 创建 Windows Phone 8 游戏开发环境
    转载:Windows Phone 8.1 投影我的屏幕使用教程
    NHibernate 中使用 nvarchar(max) 类型
  • 原文地址:https://www.cnblogs.com/doudou2018/p/10416043.html
Copyright © 2011-2022 走看看