zoukankan      html  css  js  c++  java
  • ApplicationContextAware获取bean

    ApplicationContextAware获取bean

    概述

    • 在某些特殊的情况下,Bean需要实现某个功能,但该功能必须借助于Spring容器才能实现,此时就必须让该Bean先获取Spring容器,然后借助于Spring容器实现该功能。为了让Bean获取它所在的Spring容器,可以让该Bean实现ApplicationContextAware接口。
    • Spring容器会检测容器中的所有Bean,如果发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContextAware()方法,调用该方法时,会将容器本身作为参数传给该方法——该方法中的实现部分将Spring传入的参数(容器本身)赋给该类对象的applicationContext实例变量,因此接下来可以通过该applicationContext实例变量来访问容器本身。

    使用

    public class SpringContextHolder implements ApplicationContextAware {  
        private static ApplicationContext applicationContext = null;  
      
        /** 
         * 获取静态变量中的ApplicationContext. 
         */  
        public static ApplicationContext getApplicationContext() {  
            assertContextInjected();  
            return applicationContext;  
        }  
      
        /** 
         * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 
         */  
        @SuppressWarnings("unchecked")  
        public static <T> T getBean(String name) {  
            assertContextInjected();  
            return (T) applicationContext.getBean(name);  
        }  
      
        /** 
         * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 
         */  
        public static <T> T getBean(Class<T> requiredType) {  
            assertContextInjected();  
            return applicationContext.getBean(requiredType);  
        }  
      
        /** 
         * 清除SpringContextHolder中的ApplicationContext为Null. 
         */  
        public static void clearHolder() {  
            applicationContext = null;  
        }  
      
        /** 
         * 实现ApplicationContextAware接口, 注入Context到静态变量中. 
         */  
        @Override  
        public void setApplicationContext(ApplicationContext applicationContext) {  
            SpringContextHolder.applicationContext = applicationContext;  
        }  
      
        /** 
         * 检查ApplicationContext不为空. 
         */  
        private static void assertContextInjected() {  
            Validate.validState(applicationContext != null,  
                    "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");  
        }  
      
    } 
    
  • 相关阅读:
    file类中,命令记录
    Java中有多个异常, 如何确定捕获顺序(多个catch),先从上到下执行,判断异常的大小,如果包含捕到异常,就进入这个catch,后面的就不再执行
    try....fail....catch...Assert 模式的测试, fail是Junit中的功能
    java.io.FileNotFoundException异常,一是“拒绝访问”,二是“系统找不到指定路径”
    [1]IP地址查询
    支付宝地铁SDK使用失败记录
    食神
    【初等数论】 04
    【初等数论】 03
    【初等数论】 02
  • 原文地址:https://www.cnblogs.com/frankltf/p/11383897.html
Copyright © 2011-2022 走看看