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属性未注入");
            }
        }
    }
    
  • 相关阅读:
    洛谷P3292 [SCOI2016]幸运数字 线性基+倍增
    2019牛客暑期多校第五场题解ABGH
    暑假集训-8.1总结
    主席树
    2019HDU多校第四场题解
    洛谷P4570 [BJWC2011]元素 线性基
    暑假集训-7.31总结
    线性基总结
    Proj. THUIoTFuzz Paper Reading: One Engine to Fuzz 'em All: Generic Language Processor Testing with Semantic Validation
    UVALive5876-Writings on the Wall-KMP
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/13186049.html
Copyright © 2011-2022 走看看