Spring在web应用中获得Bean的方法 实现getBean方法

来源:互联网 发布:java io流实例 编辑:程序博客网 时间:2024/05/20 06:25

1.新建类,并实现 org.springframework.context.ApplicationContextAware 接口.

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.abc.framework.util;  
  2.   
  3. import org.springframework.beans.BeansException;  
  4. import org.springframework.context.ApplicationContext;  
  5. import org.springframework.context.ApplicationContextAware;  
  6.   
  7. /** 
  8.  * 在容器启动后,也可以通过 getBean(String name) 得到对象 
  9.  * @author Administrator 
  10.  * <!-- 需要在spring.xml 里写 --> 
  11.  * <bean class="com.abc.framework.util.ApplicationContextHandle" lazy-init="false"/> 
  12.  */  
  13. public class ApplicationContextHandle implements ApplicationContextAware{  
  14.     private static ApplicationContext applicationContext;  
  15.       
  16.     @Override  
  17.     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
  18.         ApplicationContextHandle.applicationContext = applicationContext;  
  19.     }  
  20.   
  21.     /**  
  22.      * 获取对象  
  23.      * 这里重写了bean方法,起主要作用  
  24.      * @param name  
  25.      * @return Object 一个以所给名字注册的bean的实例  
  26.      * @throws BeansException  
  27.      */    
  28.     public static Object getBean(String name) throws BeansException {  
  29.         return applicationContext.getBean(name);    
  30.     }  
  31. }  

2.在spring.xml内添加:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <bean class="com.abc.framework.util.ApplicationContextHandle" lazy-init="false"/>  

3.应用:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private static final AttachmentService as = (AttachmentService)ApplicationContextHandle.getBean("attachmentService");  
0 0