Spring listener 中@Autoweird注入失败解决方法
listener中无法使用spring @autowired自动注入,因为Listener不属于spring容器,故spring容器的注入功能无法在listener中生效。这时就需要从spring 上下文中获取,最好的办法是写一个spring上下文获取bean的工具类。
代码如下:
1 @Service 2 public class SpringContextHolder implements ApplicationContextAware, DisposableBean { 3 private static ApplicationContext applicationContext = null; 4 5 6 /** 7 * 取得存储在静态变量中的ApplicationContext. 8 */ 9 public static ApplicationContext getApplicationContext() { 10 assertContextInjected(); 11 return applicationContext; 12 } 13 14 /** 15 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. 16 */ 17 @SuppressWarnings("unchecked") 18 public static <T> T getBean(String name) { 19 log.debug("从SpringContextHolder中取出Bean:" + name); 20 assertContextInjected(); 21 return (T) applicationContext.getBean(name); 22 } 23 24 /** 25 * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. 26 */ 27 public static <T> T getBean(Class<T> requiredType) { 28 assertContextInjected(); 29 return applicationContext.getBean(requiredType); 30 } 31 32 /** 33 * 清除SpringContextHolder中的ApplicationContext为Null. 34 */ 35 public static void clearHolder() { 36 log.debug("清除SpringContextHolder中的ApplicationContext:" 37 + applicationContext); 38 applicationContext = null; 39 } 40 41 /** 42 * 实现ApplicationContextAware接口, 注入Context到静态变量中. 43 */ 44 @Override 45 public void setApplicationContext(ApplicationContext applicationContext) { 46 47 if (SpringContextHolder.applicationContext != null) { 48 log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); 49 } 50 51 SpringContextHolder.applicationContext = applicationContext; // NOSONAR 52 } 53 54 /** 55 * 实现DisposableBean接口, 在Context关闭时清理静态变量. 56 */ 57 @Override 58 public void destroy() throws Exception { 59 SpringContextHolder.clearHolder(); 60 } 61 62 /** 63 * 检查ApplicationContext不为空. 64 */ 65 private static void assertContextInjected() { 66 if(applicationContext == null) { 67 throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder."); 68 } 69 }
调用方法:
MqService mqService = SpringContextHolder.getBean(MqService.class);
注:spring下需要在xml配置文件中配置改类,spring boot要添加@service注解
posted on 2018-11-19 15:58 handsonalex 阅读(505) 评论(0) 编辑 收藏 举报