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();
        }
    
    }
  • 相关阅读:
    CrawlSpiders
    从抓取Tencent中学习Scrapy
    对象返回规范的url的两种方式的两种方式
    多对多关系的额外字段
    Django定时任务
    Scripy学习(一)
    Django开发博客一(搭建模型和准备数据)
    求并集
    求子集、交集
    java数学函数Math类中常用的方法
  • 原文地址:https://www.cnblogs.com/jxd283465/p/11939932.html
Copyright © 2011-2022 走看看