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属性未注入");
            }
        }
    }
    
  • 相关阅读:
    jQuery实现动态搜索显示功能
    面试
    Struts1和Struts2的区别和对比(完整版)
    JAVA调用增删改的存储过程
    Spring MVC入门
    jQuery Ajax通用js封装
    js ==与===区别
    shell脚本awk
    C++对象模型初窥
    再见,2021
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/13186049.html
Copyright © 2011-2022 走看看