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"); 
  • 相关阅读:
    ASP.NET MVC路由模块
    线程安全的单例模式
    MVC自带表单效验
    MSsql 中 in 语法排序的说明
    Web.Config配置错误页面处理
    WCF基本应用
    .NET微信自定义分享标题、缩略图、超链接及描述的设置方法
    .NET微信通过授权获取用户的基本信息
    C#中获取服务器IP,客户端IP以及网卡物理地址
    .NET获取客户端、服务器端的信息
  • 原文地址:https://www.cnblogs.com/shihao/p/2321330.html
Copyright © 2011-2022 走看看