SpringContextUtil public class SpringContextUtils implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext; private static Logger logger = LoggerFactory.getLogger(SpringContextUtils.class); /
public class SpringContextUtils implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext; private static Logger logger = LoggerFactory.getLogger(SpringContextUtils.class); /** * 获得存储在静态变量中的ApplicationContext * @return */ public static ApplicationContext getApplicationContext () { try { assertContextInjected(); } catch (Exception e) { e.printStackTrace(); return null; } return applicationContext; } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. * @param name * @param* @return */ public static T getBean (String name) { try { assertContextInjected(); } catch (Exception e) { e.printStackTrace(); return null; } return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. * @param requireType * @param * @return */ public static T getBean (Class requireType) { try { assertContextInjected(); } catch (Exception e) { e.printStackTrace(); return null; } return applicationContext.getBean(requireType); } /** *清除SpringContextHolder中的ApplicationContext为Null. */ public static void clearHolder () { if (logger.isDebugEnabled()) { logger.debug("清除SpringContext中的ApplicationContext:"+ applicationContext); } applicationContext = null; } /** *实现ApplicationContextAware接口, 注入Context到静态变量中. * @throws Exception */ @Override public void destroy() throws Exception { SpringContextUtils.clearHolder(); } /** *实现DisposableBean接口, 在Context关闭时清理静态变量. * @param applicationContext * @throws BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (logger.isDebugEnabled()) { logger.debug("注入ApplicationContext到SpringContextHolder:{}",applicationContext); } SpringContextUtils.applicationContext = applicationContext; } /** * 检查ApplicationContext不为空 */ private static void assertContextInjected () throws Exception { if (applicationContext == null) { throw new Exception("applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder."); } } }