在线程中利用@Autowire或者@Resource注入对象,会出现对象为空的情况,如下:
@Service
public class TestRunnable implements Runnable {
@Resource
private TestService ts;
public TestRunnable(TestService ts){
this.ts = ts
}
@Override
public void run(){
System.out.println(ts.doSomething());
}
@Service
public class TestService {
public String doSomething(){
return "do";
}
}
@Controller
public class SpringMultiThreadTest{
@Test
public void testSpringBean(){
new Thread(new TestRunnable()).start();
}
}
上述代码第8行会报错,因为ts实例为null。分析原因我们能发现,第22行new Thread(new TestRunnable()).start();有个非常明显的问题,new Thread()中传入的对象TestRunnable()是手动new出来的,自然不在容器的管辖范围,因此容器不会为TestRunnable对象中的TestService成员注入实例,为了解决这个问题,总结了四个方法,如下。
1.将TestRunnable()交由容器管理,这样