zoukankan      html  css  js  c++  java
  • 线程中调用service方法出错

    public class PnFileTGIComputeThread implements Runnable {
        @Resource
        private AppUsedService   appUsedService;
    //    AppUsedService appUsedService = (AppUsedService) AllBean.getBean("appUsedService");
        public  String taskId;
        public  int  cityId;
        public PnFileTGIComputeThread(String name, int cityId){
            this.taskId = name;
            this.cityId = cityId;
        }
        @Override
        public void run() {
            try {
                this.appUsedService.doSaveAzTaskAppUsedInfoCity(Integer.valueOf(taskId),cityId);
            } catch (Exception e){
               e.printStackTrace();
            }
        }
    }
    新建了一个线程,然后再主线程中去实例化本线程,启动线程。DUG问题是,线程启动后,参数也都传过来了,但是通过注解来注入的service一直是null值。

    老办法,翻了度娘的牌子,找到问题,在线程中为了线程安全,是防注入。没办法,要用到这个类啊。只能从bean工厂里拿个实例了

    public class AllBean implements ApplicationContextAware{
       
        private static ApplicationContext applicationContext; 
       
        public void setApplicationContext(ApplicationContext context) {
           AllBean.applicationContext = context;
           }
       
        public static Object getBean(String name){
             return applicationContext.getBean(name);
        }
        
         public static ApplicationContext getApplicationContext() {  
              return applicationContext;  
          }  
    }
    getbean方法,获取上下文中的bean, 不过呢要有点问题,这个AllBean类需要在在Bean工厂中注册下
    <bean id="allBean" class="xxxxx.AllBean"  />
      想要啥东西,现在都可以直接去getBean,例如:
    AppUsedService appUsedService = (AppUsedService) AllBean.getBean("appUsedService");
    好的,线程正常启动了。
  • 相关阅读:
    单例类
    日期类2
    日历类
    日期转换类
    抓取网页内容并截图
    关于计时器与多线程
    让页面上图片不变形
    Thread 调用方法的方式
    语音放大缩小
    阻止Enter键回发到服务端Asp.net
  • 原文地址:https://www.cnblogs.com/nankeyimengningchenlun/p/9186207.html
Copyright © 2011-2022 走看看