使用Spring+springMVC+mybatis框架建立的项目如果需要使用到多线程可能会出现一个问题——无法创建Bean
错误代码一般为:
Post-processing failed of bean type [class com.ccbupt.checkwork.checkwork.service.impl.CheckworkServiceImpl] failed; nested exception is java.lang.IllegalStateException: @Resource annotation is not supported on static fields
这是因为spring框架考虑到线程安全的问题,使得@Resource在多线程中被禁用。
不过,有时候需要开线程完成一些小的或者后台的功能时,我们还是希望能使用到service和dao
这位博主:http://zhenxingluo918.iteye.com/blog/2223761 在这篇文章中使用了4种方法:
1.设置为静态
2.在这个线程的构造函数中把service实例传过去,然后再启动。如:new MyThread(myService).start()
3.让service或者dao的实现类实现Runnable这个接口,然后把你的线程的逻辑写在run方法里,启动的时候,直接this.start()就行。注意除了要在service的实现类中实现Runnable接口外,还应该在service接口中继承Runnable接口。
4.直接new一个实例
我在service层使用了第4种方法直接创建实例。但是在dao层发现,由于使用了mybatis无法直接将mapper实例化,于是只好另辟蹊径。
这里参考了博客:http://blog.csdn.net/hujin_forever/article/details/52150632
最后在dao层使用了实现接口ApplicationContextAware的方式,代码如下
@Component
public class SpringBeanUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringBeanUtils.applicationContext=applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static T getBean(String name,Class requiredType){
return applicationContext.getBean(name, requiredType);
}
}
然后再Spring-SpringMVC.xml配置中加入该bean:
最后使用getBean方法直接创建bean实例即可:<bean id="springBeanUtils" class="com.hujin.common.util.SpringBeanUtils"/>
private CheckworkMapper checkworkMapper=(CheckworkMapper) SpringBeanUtils.getBean("checkworkMapper");
要注意getBean中的首字母要小写,以及该类不需要写@service标签