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属性未注入");
            }
        }
    }
    
  • 相关阅读:
    Entropy
    MonkeyEatsPeach
    python中使用可选参数
    java中二元数组的构建
    静态语言和动态语言
    开胃菜
    python 工具箱
    python处理多层嵌套列表
    小球落体
    LoadRunner:Error 27796
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/13186049.html
Copyright © 2011-2022 走看看