zoukankan      html  css  js  c++  java
  • 【Java】ApplicationContext应用上下文工具类

    @Slf4j
    @Service
    public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    
        private static ApplicationContext applicationContext = null;
    
        /**
         * 取得存储在静态变量中的ApplicationContext.
         */
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        /**
         * 实现ApplicationContextAware接口, 注入Context到静态变量中.
         */
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) {
            SpringContextHolder.applicationContext = applicationContext;
        }
    
        /**
         * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
         */
        @SuppressWarnings("unchecked")
        public static <T> T getBean(String name) {
            return (T) applicationContext.getBean(name);
        }
    
        /**
         * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
         */
        public static <T> T getBean(Class<T> requiredType) {
            return applicationContext.getBean(requiredType);
        }
    
        /**
         * 清除SpringContextHolder中的ApplicationContext为Null.
         */
        public static void clearHolder() {
            if (log.isDebugEnabled()) {
                log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
            }
            applicationContext = null;
        }
    
        /**
         * 发布事件
         *
         * @param event
         */
        public static void publishEvent(ApplicationEvent event) {
            if (applicationContext == null) {
                return;
            }
            applicationContext.publishEvent(event);
        }
    
        /**
         * 实现DisposableBean接口, 在Context关闭时清理静态变量.
         */
        @Override
        public void destroy() {
            SpringContextHolder.clearHolder();
        }
    
    }
  • 相关阅读:
    for循环,pydev提示未使用的变量,解决办法
    sc 与net命令的区别
    Selenium测试Ajax程序(转)
    Python yield 使用浅析(转)
    python操作Excel读写--使用xlrd
    Python操作Mysql实例代码教程在线版(查询手册)
    MySQL之alter语句用法总结
    使用WebDriver遇到的那些坑(转)
    python 列表转为字典的两个小方法
    python
  • 原文地址:https://www.cnblogs.com/jxd283465/p/11939932.html
Copyright © 2011-2022 走看看