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



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

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

[java] view plain copy

在CODE上查看代码片派生到我的代码片

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

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”);