当前位置 : 主页 > 编程语言 > c++ >

SpringContextUtil

来源:互联网 收集:自由互联 发布时间:2021-06-30
SpringContextUtil public class SpringContextUtils implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext; private static Logger logger = LoggerFactory.getLogger(SpringContextUtils.class); /
SpringContextUtil
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."); } } }
     
    
   
  
 
上一篇:EhcacheUtil
下一篇:Oracle全方位记录
网友评论