线程中调用service方法出错

来源:互联网 发布:新西兰特卡波星空 知乎 编辑:程序博客网 时间:2024/06/05 02:27

问题已经解决,不过还会要记录下。

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

原创粉丝点击