-
问题描述
Spring项目中创建的线程通过@Autowired自动注入bean对象,但是bean一直为null,并引起NullPointerException异常。
-
问题原因
创建的线程不在Spring容器中,无法获得Spring容器中的bean对象。
-
解决办法
通过java代码手动获取。
-
代码示例
(1)继承ApplicationContextAware接口,复写setApplicationContext方法,用于获取应用上下文,并添加@Component注解用于加载。
@Component
public class BeanContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanContext.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
(2)创建的线程中,通过代码手动获取,如获取OperateHandler对象。
public class SendWorker implements Runnable {
private OperateHandler handler;
public SendWorker() {
this.handler = BeanContext.getApplicationContext().getBean(OperateHandler.class);
}
@Override
public void run() {
//...
}
}