Java普通类获取Spring XML中Bean的方法总结

这篇文章是过于理论的东西,这里有一份能够直接使用的封装好的源码:

   Bean工厂(com.springframework.beans.factory.BeanFactory)是Spring框架最核心的接口,它提供了高级IoC的配置机制。BeanFactory使管理不同类型的Java对象成为可能,应用上下文(com.springframework.context.ApplicationContext)建立在BeanFactory基础之上,提供了更多面向应用的功能,它提供了国际化支持和框架事件体系,更易于创建实际应用。我们一般称BeanFactory为IoC容器,而称ApplicationContext为应用上下文。但有时为了行文方便,我们也将ApplicationContext称为Spring容器。
   对于两者的用途,我们可以进行简单划分:BeanFactory是Spring框架的基础设施,面向Spring本身;ApplicationContext面向使用Spring框架的开发者,几乎所有的应用场合我们都直接使用ApplicationContext而非底层的BeanFactory。
   ApplicationContext的初始化和BeanFactory有一个重大的区别:BeanFactory在初始化容器时,并未实例化Bean,直到第一次访问某个Bean时才实例目标Bean;而ApplicationContext则在初始化应用上下文时就实例化所有单实例的Bean。因此ApplicationContext的初始化时间会比BeanFactory稍长一些

   本文不涉及通过@Resource、@Autowired 自动注入,仅仅通过ApplicationContext获取Sping配置文件中的Bean。

   要获取XML中配置的Bean,最关键的是获取org.springframework.context.ApplicationContext

   第一种获取ApplicationContext的方法:

import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;ApplicationContext applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");或者import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;privateApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");

   这种方式实例化applicationContext是非常耗时的,仅仅推荐使用在程序需要通过配置文件手工初始化Spring的情况。
   ApplicationContext的主要实现类是ClassPathXmlApplicationContext和FileSystemXmlApplicationContext,前者默认从类路径加载配置文件,后者默认从文件系统中装载配置文件

   第二种获取ApplicationContext的方法:

   Spring提供了WebApplicationContextUtils.getWebApplicationContext方法来获取ApplicationContext对象。

import org.springframework.web.context.support.WebApplicationContextUtils;import javax.servlet.ServletContext;ApplicationContext applicationContext=WebApplicationContextUtils.getWebApplicationContext(ServletContext servletContext);//ServletContext servletcontext = request.getSession().getServletContext();

   通过javax.servlet.ServletContext 获取到ApplicationContext实例对象,这意味着,必须使用到request、session等等。
   这样,就不能把ApplicationContext对象设置为成员变量。需要在每个具体的方法中通过request、session等获取到ServletContext再获取ApplicationContext实例。
   因此,此方法仅仅推荐使用在可以获取到ServletContext对象的Web项目中,并且不需要将ApplicationContext对象定义为成员变量的情况下。

   注意:当使用WebApplicationContextUtils获取ApplicationContext实例时,需要在web.xml配置文件中添加org.springframework.web.context.ContextLoaderListener监听器,否则获取不到ApplicationContext对象,返回Null。

   配置文件:web.xml

<!--ContextLoaderListener自动注入 applicationContext,通过WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext())获取 --><!--Spring配置文件加载位置 --><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring/appContext.xml,/WEB-INF/spring/appInterceptor.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

   第三种获取ApplicationContext的方法:

   通过继承org.springframework.context.support.ApplicationObjectSupport使用getApplicationContext()获取ApplicationContext实例
   Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

   第四种获取WebApplicationContext的方法:

   通过继承org.springframework.web.context.support.WebApplicationObjectSupport使用getWebApplicationContext() 获取到org.springframework.web.context.WebApplicationContext
   由于Web应用比一般的应用拥有更多的特性,因此WebApplicationContext扩展了ApplicationContext。WebApplicationContext定义了一个常量ROOT_WEB_APPLICATION_ CONTEXT_ATTRIBUTE,在上下文启动时,WebApplicationContext实例即以此为键放置在ServletContext的属性列表中,因此我们可以直接通过以下语句从Web容器中获取WebApplicationContext:

WebApplicationContext wac = (WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

   第五种获取ApplicationContext的方法:

   通过实现org.springframework.context.ApplicationContextAware接口,实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。 Spring初始化时,会通过该方法将ApplicationContext对象注入。

   第三、四、五种方法都需要将类配置在Spring配置文件中:

<!--假定ApplicationContextTool为继承或者实现了第三、四、五种方法的具体实现类--><beanclass="com.twovv.utils.ApplicationContextTool"></bean>

   否则将获取不到ApplicationContext,返回Null。

 

 

第三、四、五种方法实现:

http://www.cnblogs.com/badwood316/archive/2009/03/22/1419211.html

 
 
 因为写了些bean作为quartz的任务用spring配置了,但有些时候需要在别的类中使用这些bean,没有太仔细去研究spring,依稀记得有个getBean,到网上g了一把,发现方法不止一种,选了一种最简单的方法:

     主要思路是使用静态变量保存全局的应用上下文,在spring框架中配置,框架加载时会把全局上下文实例传入。

     

 

 

 

 

 

 

众所周知,Spring框架将DI模式发挥到了极至,因此,系统里面用Spring管理的Bean相互之间的获取是非常方便的,只要使用者提供一个setter方法并在配置文件中配置该属性就可以。

但是,对于系统中非Spring框架管理的类,如果需要获取Spring管理的类,或者,程序中需要动态的根据Beanid来获取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对象,然后在通过它获取需要的类实例。
这个类提供了方便的功能,这样你就不必去记 ServletContext 中属性的名字。 它的 getWebApplicationContext() 方法在 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 这个键值不对应任何对象的时候将返回 null。不过,为了避免在应用中得到 NullPointerExceptions ,我们推荐你使用 getRequiredWebApplicationContext() 方法。这个方法在ApplicationContext 缺失的时候会抛出一个异常。 
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。 
  方法三:继承自抽象类ApplicationObjectSupport 
 抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。
 

方法四:继承自抽象类WebApplicationObjectSupport 类似上面方法,调用getWebApplicationContext ()获取WebApplicationContext
 
方法五:实现接口ApplicationContextAware 实现该接口的 setApplicationContext( ApplicationContext  context)方法,并保存 ApplicationContext  对象。Spring初始化时,会通过该方法将 ApplicationContext  对象注入。
我自己是在web.xml中配置,然后用一个监听器调用一个类直接读取,在tomcat启动时执行
web.xml
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/config/spring/applicationContext.xml</param-value>
  </context-param>
<listener>
    <listener-class>com.wzw.listener.SpringListener</listener-class>
  </listener>
SpringListener package com.wzw.listener;
 import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.wzw.spring.common.SpringBeanFactory;
 public class SpringListener implements ServletContextListener {
  public void contextInitialized(ServletContextEvent sce) {
  // TODO Auto-generated method stub
String relativePath = sce.getServletContext().getInitParameter(
"contextConfigLocation");
String realPath = sce.getServletContext().getRealPath(relativePath); 
SpringBeanFactory.init(realPath);
 }
 
 public void contextDestroyed(ServletContextEvent arg0) {
  // TODO Auto-generated method stub
 SpringBeanFactory.clear();
}

}
监听器调用的类

package com.wzw.spring.common;

import java.util.Locale;
import org.apache.struts.action.ActionMessage;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.ApplicationContext;


public class SpringBeanFactory {
 
  private static ApplicationContext context;


   /**
    * 在应用程序启动时配置spring框架
    *
    * @param filePath
    */
   public static void init(String filePath) {

    if (context == null) {
       context = new FileSystemXmlApplicationContext(filePath);
    }
  }
   public static ApplicationContext getContext(){
    return context;
   }

   /**
    * 方法用于获取业务对象。
    *
    * @param beanName
    * @return
    */
   public static Object getBusinessOjbect(String beanName) {
    return context.getBean(beanName);
   }
   /**
    * 在应用程序关闭时,清空spring框架配置信息。
    */
   public static void clear() {
    if (context != null) {
     context = null;
    }
   }
}

这样就可以取到application,只要配置正确,再通过application取bean那是轻而易举的事!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值