场景如下:
bean都由spring管理,在某个业务里需要启动新的线程去完成通讯的工作,在线程中根据通讯返回的状态作更改,这时需要在线程中用到某个业务bean,但是使用常规的@Resource无法注入。。。(查了查说是spring因为考虑到线程安全问题,不支持注入)
1. 目前我通过在业务bean中启动线程的时候,通过构造函数或者方法形参(传参方式)将业务bean实例传到线程中使用的。 2. 不能在线程中手动拿bean,每次初始化spring容器,受不了(容器、DB。。。),刚开始这样做就把db搞挂了 3. 单独维护数据源?然后通过此源拿bean?试过,可行,但感觉开销太大
不知道有什么优良的解决方案没,或者说如何避免形成此景?
在线程的构造器中把这个需要注入的bean传递进去
遇到自动注入有问题的情况,可以考虑主动去获取bean。
建立这样一个工具类,放到Spring容器中,就可以用context.getBean("beanName")的方式去拿了。
public class ContextUtil implements ApplicationContextAware{ private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getContext(){ return context; } public static Object getBean(String beanName) { return context.getBean(beanName); } }
如果是web应用,可以直接通过classLoader拿到context实例,获取bean
public class SpringBeanUtil { private static ApplicationContext applicationContext; public static <T> T getBean(Class<T> clazz, String beanName) { ApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); if (context == null) { context = applicationContext; } return (T) context.getBean(beanName); } public static void setApplicationContext(ApplicationContext applicationContext) { SpringBeanUtil.applicationContext = applicationContext; } }