赞
踩
在项目开发过程中,有碰到多线程下用@Autowired或@Resource注入失败,报NullPointException的情况,这就要从Spring对Bean的管理来说明了,这是是因为创建的多线程无法获取到Spring容器中的bean。这体现了熟悉框架原理和底层实现的重要性。
可以有以下解决方法:
1、通过内部类来实现
@Component
public class ThreadBean {
@Autowired
MyService myService;
public void execute(){
ExecutorService executorService= Executors.newCachedThreadPool();
executorService.execute(new MyTread());
}
private class MyTread implements Runnable{
@Override
public void run() {
dosomeThing();
}
}
public void dosomeThing(){
System.out.println("do something"+myService.getTime());
}
}
将该类作为Bean组件调用,实现多线程
@Component
public class QuartzTask {
@Autowired
ThreadBean threadBean;
@Scheduled(cron = "0/3 * * * * ? ")
public void scheduled(){
threadBean.execute();
}
}
2、编码通过Spring的上下文对象获取bean
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextProvider.applicationContext = applicationContext;
}
private static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanName) {
if (null==beanName||"".equals(beanName)) {
return "bean name is required!";
}
return getApplicationContext()==null?null:getApplicationContext().getBean(beanName);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
}
3、通过构造函数来获取
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。