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

    加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的

    public void setApplicationContext(ApplicationContext context) throws BeansException

    方法,获得ApplicationContext 对象。

    前提必须在Spring配置文件中指定该类。

     
    Java代码  收藏代码
    1. public class SpringContextHolder implements ApplicationContextAware {     
    2.     
    3.      /**   
    4.       * 以静态变量保存ApplicationContext,可在任意代码中取出ApplicaitonContext.   
    5.       */    
    6.     private static ApplicationContext context;     
    7.     
    8.     /**   
    9.      * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.   
    10.      */    
    11.     public void setApplicationContext(ApplicationContext context) {     
    12.         SpringContextHolder.context =context;     
    13.     }        
    14.     public static ApplicationContext getApplicationContext() {     
    15.         return context;     
    16.     }     
    17.     /**   
    18.      * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.   
    19.      */    
    20.     public static <T> T getBean(String name) {     
    21.         return (T) context.getBean(name);     
    22.     }     
    23. }    
     
     
     
    bean中:
    Xml代码  收藏代码
    1. <bean id="springContextHolder" class="com.enation.framework.context.spring.SpringContextHolder" />  
     

    调用:

     

    Java代码  收藏代码
    1. ICartManager cartManager = SpringContextHolder.getBean("cartManager"); 
  • 相关阅读:
    写在彻底转向有道云笔记一个月之后
    KMP算法实现
    有道云笔记 V.S. 为知笔记
    卸载印象笔记,跟印象笔记说拜拜
    ExpandRegion for Sublime Text:快速选择文本
    Linux cat命令详解
    Vim安装插件
    Vim与正则表达式
    还没供暖
    在Linux命令行中设置并使用代理服务器
  • 原文地址:https://www.cnblogs.com/shihao/p/2321330.html
Copyright © 2011-2022 走看看