码迷,mamicode.com
首页 > 编程语言 > 详细

线程中调用service方法出错

时间:2018-06-15 13:11:22      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:save   IV   pre   info   catch   xxxxx   com   主线程   上下   

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");
好的,线程正常启动了。

线程中调用service方法出错

标签:save   IV   pre   info   catch   xxxxx   com   主线程   上下   

原文地址:https://www.cnblogs.com/nankeyimengningchenlun/p/9186207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!