---
title: "在Spring框架下获取Bean的方式总结"
author: "lvjun106"
date: "2011-11-22T16:29:17Z"
tags: []
categories: ["开源软件"]
slug: "spring-bean"
draft: false
lastmod: "2011-11-22T16:29:17Z"
id: 1272958
url: "https://lvjun106.iteye.com/blog/1272958"
---

转
最后一句话最重要

注:经分析 原文的三种方法,实现上是一种方法:因为     ApplicationObjectSupport  实现了接口ApplicationContextAware  ,而WebApplicationObjectSupport则继承了ApplicationObjectSupport 


原作者：陈博MSN: Bochen_pku@hotmail.com
http://blog.csdn.net/shiningstone/archive/2005/09/08/475219.aspx

 

众所周知，Spring框架将DI模式发挥到了极至，因此，系统里面用Spring管理的Bean相互之间的获取是非常方便的，只要使用者提供一个setter方法并在配置文件中配置该属性就可以。

 

但是，对于系统中非Spring框架管理的类，如果需要获取Spring管理的类，或者，程序中需要动态的根据Bean的id来获取Bean实例，不可能事先为该类提供所有需要的Bean属性的setter方法，在类似这样的情况下，获取Spring框架管理的类实例的方法有多种，现在简单总结如下：

 


 


方法一：在初始化时保存ApplicationContext对象

 

     代码：
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
    ac.getBean("beanId");
    说明：
    这种方式适用于采用Spring框架的独立应用程序，需要程序通过配置文件手工初始化Spring的情况。
 
方法二：通过Spring提供的工具类获取ApplicationContext对象
    代码：
 import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)
    ac1.getBean("beanId");
    ac2.getBean("beanId");
        说明：
        这种方式适合于采用Spring框架的B/S系统，通过ServletContext对象获取ApplicationContext对象，然后在通过它获取需要的类实例。
        上面两个工具方式的区别是，前者在获取失败时抛出异常，后者返回null。
 
    方法三：继承自抽象类ApplicationObjectSupport
         说明：
     抽象类ApplicationObjectSupport提供getApplicationContext()方法，可以方便的获取到ApplicationContext。Spring初始化时，会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四：继承自抽象类WebApplicationObjectSupport
         说明：
         类似上面方法，调用getWebApplicationContext()获取WebApplicationContext
 
    方法五：实现接口ApplicationContextAware
         说明：
     实现该接口的setApplicationContext(ApplicationContext context)方法，并保存ApplicationContext 对象。Spring初始化时，会通过该方法将ApplicationContext 对象注入。
 
以上方法适合不同的情况，请根据具体情况选用相应的方法。
这里值得提一点的是，系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了，因为这些类是知道它们是运行在Spring框架上的，因此，系统中，应该尽量的减少这类应用，使系统尽可能的独立于当前运行环境，尽量通过DI的方式获取需要的服务提供者。