技术笔记:多线程(Runnable)类或者是监听器中使用Autowired自动注入出现null的问题
一、原因分析:
在多线程时使用@Autowired总是获取不到bean,原因是:new thread不在spring容器中,也就无法获得spring中的bean对象
二、解决方案:
手动获取
代码实现如下:
package com.test.configs; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class BeanContext implements ApplicationContextAware { private static ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { BeanContext.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext(){ return applicationContext; } @SuppressWarnings("unchecked") public static <T> T getBean(String name) throws BeansException { return (T)applicationContext.getBean(name); } public static <T> T getBean(Class<T> clz) throws BeansException { return (T)applicationContext.getBean(clz); } }
线程类中的使用使用方法:
package com.test.handler; import com.test.configs.BeanContext; import com.test.service.TestService; import com.test.model.User; public class TestHandler implements Runnable { private User user; private TestService testService; @Override public void run() { this.testService= BeanContext.getApplicationContext().getBean(TestService.class); //这里就可以使用service逻辑接口中的方法了 User user=testService.queryUserById(11); } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
若是是监听器类的话,只需要在监听器的执行方法中执行下面的代码就可以实现:
TestService testService= BeanContext.getApplicationContext().getBean(TestService.class);
至此,多线程类中使用调用service接口为null的问题就搞定了!
我的网站 http://www.a-du.net