zoukankan      html  css  js  c++  java
  • 【Spring__ApplicationContext】SpringContextHolder

    1、配置

    全局设置ApplicationContext需在spring配置文件配置<bean class="com.kikyo.listener.SpringContextHolder" lazy-init="false"/>,在spring在初始化时,扫描实现了ApplicationContextAware的类,并调用setApplicationContext

    2、代码

    package com.kikyo.listener;
    
    import org.springframework.beans.factory.DisposableBean;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.context.annotation.Lazy;
    import org.springframework.stereotype.Service;
    
    @Service
    @Lazy(false)
    public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    
        private static ApplicationContext applicationContext = null;
    
        public static ApplicationContext getApplicationContext() {
            assertContextInjected();
            return applicationContext;
        }
    
        @SuppressWarnings("unchecked")
        public static <T> T getBean(String name) {
            assertContextInjected();
            return (T) applicationContext.getBean(name);
        }
    
        public static <T> T getBean(Class<T> requiredType) {
            assertContextInjected();
            return applicationContext.getBean(requiredType);
        }
    
        public static void clearHolder() {
            applicationContext = null;
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) {
            SpringContextHolder.applicationContext = applicationContext;
        }
    
        @Override
        public void destroy() throws Exception {
            SpringContextHolder.clearHolder();
        }
    
        private static void assertContextInjected() {
            if (applicationContext == null) {
                throw new RuntimeException("applicaitonContext属性未注入");
            }
        }
    }
    
  • 相关阅读:
    30行左右代码实现一个类似httprunner的接口框架
    Python中一些高效的数据操作
    使用jsonpath解析多层嵌套的json响应信息
    操作系统的启动流程
    I/O延迟
    存储器
    多线程和多核芯片
    CPU详解(内核态和用户态)
    操作系统
    计算机组成
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/13186049.html
Copyright © 2011-2022 走看看