天天看点

spring 在Thread中注入@[email protected]失败,总为null~解决

参考:http://bailong139.blog.163.com/blog/static/2072381002014630114537506/

背景:

       我用@service或者@resposity声明了一个bean,给sping管理。现在我有个需求,就是用到Thread去监控,但是这个线程需要用我的service或者dao,然后我习惯性的在继承了Thread类或者实现了Runnable的类里写了如下:    @Resource   private MyService myService;   但是运行的时候,进入到这个线程,这个myServcie总为null,也就是注入失败。 解决办法: 1.第一种(可以) 就是我在启动这个线程的时候,在这个线程的构造函数中把我的service实例传过去,然后再启动。 new MyThread(myService).start()

private MyService myService;
this.myService=  SpringUtils.getApplicationContext().getBean(MyService .class);
           
public class SpringUtils implements ApplicationContextAware{

	private static ApplicationContext applicationContext;
	
	@SuppressWarnings("static-access")
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
		
	}

	public static ApplicationContext getApplicationContext(){
		return applicationContext;
	}
	
	public static Object getBean(String name) throws BeansException{
		return applicationContext.getBean(name);
	}
}
           

2.第二种(可以,未亲测) 就是让我的service或者dao的实现类实现Runnable这个接口,然后把你的线程的逻辑写在run方法里,启动的时候,直接this.start()就行。注意除了要在service的实现类中实现Runnable接口外,还应该在service接口中继承Runnable接口。 对于我的情况,我是直接在dao里实现了Runnable,然后用的线程池启动的,如下:pool.execute(this);

3.还有就是直接new一个实例。 但是new一个实例,session = localSessionFactory.getCurrentSession(); 这个localSessionFactory也是注入进去的,这里会报null. @Autowired

public SessionFactory localSessionFactory;

继续阅读