1. ApplicationContext ac1 = new FileSystemXmlApplicationContext("com/spark/system/applicationContext.xml");//如果配置文件放在文件系统的目录下则优先使用该方式
  2. //com/spark/system/applicationContext.xml等价于"file:com/spark/system/applicationContext.xml"
  3. ac1.getBean("beanId");
  4. //ApplicationContext ac2=new ClassPathXmlApplicationContext("com/spark/system/applicationContext.xml");//如果配置文件在类路径下则优先使用该方式
  5. //com/spark/system/applicationContext.xml 等价于"classpath:com/spark/system/applicationContext.xml"
  6. ac2.getBean("beanId");

说明:

这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。


  1. public void getBean(HttpServletRequest req,HttpSession se)
  2. {
  3. // se.getServletContext() 也可以
  4. WebApplicationContext wac=(WebApplicationContext)req.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  5. wac.getBean("");
  6. }

说明:此种方式正是我们下面所提到的WebApplicationContextUtils 工具类中getWebApplicationContext(ServletContext sc) 方法的内部实现,以下方式是通过spring 提供的WebApplicationContextUtils 工具类获取WebApplicationContext

方式一:


  1. import org.springframework.web.context.support.WebApplicationContextUtils;
  2. ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)
  3. ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)
  4. ac1.getBean("beanId");
  5. ac2.getBean("beanId");

说明:

这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。

上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。

方式二:


  1. import org.springframework.web.context.WebApplicationContext;
  2. import org.springframework.web.context.support.WebApplicationObjectSupport;
  3. public class ApplicationContextUtils extends WebApplicationObjectSupport{
  4. public WebApplicationContext isgetWebApplicationContext(){
  5. return super.getWebApplicationContext();
  6. }
  7. }

继承自抽象类WebApplicationObjectSupport

说明:

抽象类WebApplicationObjectSupport 继承自ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该ApplicationObjectSupport 的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。当然直接继承ApplicationObjectSupport自己实现也可以,既然spring
提供了更方便的抽象工具类WebApplicationObjectSupport 建议使用它。以免出现问题

下面看WebApplicationObjectSupport关键源码(红色部分)


  1. /*** Eclipse Class Decompiler, copyright (c) 2012 cnfree (cnfree2000@hotmail.com) ***/
  2. package org.springframework.web.context.support;
  3. import java.io.File;
  4. import javax.servlet.ServletContext;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.support.ApplicationObjectSupport;
  7. import org.springframework.web.context.ServletContextAware;
  8. import org.springframework.web.context.WebApplicationContext;
  9. import org.springframework.web.util.WebUtils;
  10. public abstract class WebApplicationObjectSupport <span style="color:#FF0000;">extends ApplicationObjectSupport</span> implements ServletContextAware{
  11. private ServletContext servletContext;
  12. public final void setServletContext(ServletContext servletContext){
  13. if (servletContext != this.servletContext){
  14. this.servletContext = servletContext;
  15. if (servletContext != null) initServletContext(servletContext);
  16. }
  17. }
  18. protected boolean isContextRequired(){
  19. return true;
  20. }
  21. protected void initApplicationContext(ApplicationContext context){
  22. super.initApplicationContext(context);
  23. if ((this.servletContext == null)
  24. && (context instanceof WebApplicationContext)){
  25. this.servletContext = ((WebApplicationContext)context)
  26. .getServletContext();
  27. if (this.servletContext != null)
  28. initServletContext(this.servletContext);
  29. }
  30. }
  31. protected void initServletContext(ServletContext servletContext){}
  32. <span style="color:#FF0000;">protected final WebApplicationContext getWebApplicationContext()
  33. throws IllegalStateException{
  34. ApplicationContext ctx = getApplicationContext();
  35. if (ctx instanceof WebApplicationContext){ return ((WebApplicationContext)getApplicationContext()); }
  36. if (isContextRequired()){ throw new IllegalStateException(
  37. "WebApplicationObjectSupport instance [" + this
  38. + "] does not run in a WebApplicationContext but in: "
  39. + ctx); }
  40. return null;
  41. }</span>
  42. protected final ServletContext getServletContext()
  43. throws IllegalStateException{
  44. if (this.servletContext != null){ return this.servletContext; }
  45. ServletContext servletContext = getWebApplicationContext()
  46. .getServletContext();
  47. if ((servletContext == null) && (isContextRequired())){ throw new IllegalStateException(
  48. "WebApplicationObjectSupport instance ["
  49. + this
  50. + "] does not run within a ServletContext. Make sure the object is fully configured!"); }
  51. return servletContext;
  52. }
  53. protected final File getTempDir() throws IllegalStateException{
  54. return WebUtils.getTempDir(getServletContext());
  55. }
  56. }

下面是ApplicationObjectSupport源码


  1. /*** Eclipse Class Decompiler, copyright (c) 2012 cnfree (cnfree2000@hotmail.com) ***/
  2. package org.springframework.context.support;
  3. import org.apache.commons.logging.Log;
  4. import org.apache.commons.logging.LogFactory;
  5. import org.springframework.beans.BeansException;
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.context.ApplicationContextAware;
  8. import org.springframework.context.ApplicationContextException;
  9. public abstract class ApplicationObjectSupport implements
  10. ApplicationContextAware{
  11. protected final Log logger;
  12. private ApplicationContext applicationContext;
  13. private MessageSourceAccessor messageSourceAccessor;
  14. public ApplicationObjectSupport(){
  15. this.logger = LogFactory.getLog(super.getClass());
  16. }
  17. public final void setApplicationContext(ApplicationContext context)
  18. throws BeansException{
  19. if ((context == null) && (!(isContextRequired()))){
  20. this.applicationContext = null;
  21. this.messageSourceAccessor = null;
  22. }
  23. else if (this.applicationContext == null){
  24. if (!(requiredContextClass().isInstance(context))){ throw new ApplicationContextException(
  25. "Invalid application context: needs to be of type ["
  26. + requiredContextClass().getName() + "]"); }
  27. this.applicationContext = context;
  28. this.messageSourceAccessor = new MessageSourceAccessor(context);
  29. initApplicationContext(context);
  30. }
  31. else if (this.applicationContext != context){ throw new ApplicationContextException(
  32. "Cannot reinitialize with different application context: current one is ["
  33. + this.applicationContext + "], passed-in one is ["
  34. + context + "]"); }
  35. }
  36. protected boolean isContextRequired(){
  37. return false;
  38. }
  39. protected Class requiredContextClass(){
  40. return ApplicationContext.class;
  41. }
  42. protected void initApplicationContext(ApplicationContext context)
  43. throws BeansException{
  44. initApplicationContext();
  45. }
  46. protected void initApplicationContext() throws BeansException{}
  47. public final ApplicationContext getApplicationContext()
  48. throws IllegalStateException{
  49. if ((this.applicationContext == null) && (isContextRequired())){ throw new IllegalStateException(
  50. "ApplicationObjectSupport instance [" + this
  51. + "] does not run in an ApplicationContext"); }
  52. return this.applicationContext;
  53. }
  54. protected final MessageSourceAccessor getMessageSourceAccessor()
  55. throws IllegalStateException{
  56. if ((this.messageSourceAccessor == null) && (isContextRequired())){ throw new IllegalStateException(
  57. "ApplicationObjectSupport instance [" + this
  58. + "] does not run in an ApplicationContext"); }
  59. return this.messageSourceAccessor;
  60. }
  61. }

通过源码很容易看得出spring做的这两次封装是如何获取到WebApplicationContext的  当然自己也可以实现底层接口自己封装。

比如:继承自抽象类ApplicationObjectSupport,抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

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

以上方法适合不同的情况,请根据具体情况选用相应的方法。

这里值得提一点的是,系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了,因为这些类是知道它们是运行在Spring框架上的,因此,系统中,应该尽量的减少这类应用,使系统尽可能的独立于当前运行环境,尽量通过DI的方式获取需要的服务提供者。

PS:除了通过applicationContext来手动获取getBean("beanId")之外,还可以通过beanfactory工厂的.getBean("beanId")获取Bean 实例

例如:


  1. ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
  2. Resource resource=resolver.getResource("classpath:com/**/beans.xml");
  3. BeanFactory bf=new XmlBeanFactory(resource);
  4. bf.getBean("beanId");

有待研究 通过BeanFactory.getBean和ApplicationContext.getBean 的异同解释,和利弊以及使用情况。志同道合的同志可随时留言讨论,小弟欢迎大家一起学习

本文属于原创,请勿抄袭,谢谢!

关于spring获取webApplication.getBean多种途径和简单解释的更多相关文章

  1. paip.spring 获取bean getBean 没有beanid的情况下

    paip.spring 获取bean  getBean 没有beanid的情况下 spring能自动扫描带有注解的bean文件.. 作者Attilax  艾龙,  EMAIL:1466519819@q ...

  2. Spring学习总结(一)——Spring实现IoC的多种方式

    控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法.没有IoC的程序中我们使用面向对象编程对象的创 ...

  3. spring获取webapplicationcontext,applicationcontext几种方法详解

    法一:在初始化时保存ApplicationContext对象代码: ApplicationContext ac = new FileSystemXmlApplicationContext(" ...

  4. Spring实现Ioc的多种方式--控制反转、依赖注入、xml配置的方式实现IoC、对象作用域

    Spring实现Ioc的多种方式 一.IoC基础 1.1.概念: 1.IoC 控制反转(Inversion of Control) IoC是一种设计思想. 2.DI 依赖注入 依赖注入是实现IoC的一 ...

  5. spring获取webapplicationcontext,applicationcontext几种方法详解(转)

    方法一:在初始化时保存ApplicationContext对象 代码: ApplicationContext ac = new FileSystemXmlApplicationContext(&quo ...

  6. spring获取webapplicationcontext,applicationcontext几种方法详解(转载)

    转载自  http://www.blogjava.net/Todd/archive/2010/04/22/295112.html 方法一:在初始化时保存ApplicationContext对象 代码: ...

  7. spring 获取 WebApplicationContext的几种方法

    spring 获取 WebApplicationContext的几种方法 使用ContextLoader WebApplicationContext webApplicationContext = C ...

  8. Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式

    转自:http://chinazhaokeke.blog.163.com/blog/static/109409055201092811354236  Spring获取ApplicationContex ...

  9. spring获取bean的时候严格区分大小写

    如题:spring获取bean的时候严格区分大小写 配置文件helloservice.xml中配置: <dubbo:reference id="IInsurance" int ...

随机推荐

  1. Codefroces Educational Round 27 845G Shortest Path Problem?

    Shortest Path Problem? You are given an undirected graph with weighted edges. The length of some pat ...

  2. 【hdu 6038】Function

    [Link]:http://codeforces.com/contest/834/problem/C [Description] 给你两个排列a和b; a排列的长度为n,b排列的长度为m; a∈[0. ...

  3. 如何在win10上同时安装python2和python3

    哎,其实本人已经用惯了python2,听说python3的语法有很多不一样的地方,那我之前写的算法改起来岂不是日了狗了吗?所以一直没改用python3.但是谷歌的那个TensorFlow,在windo ...

  4. BZOJ 1696 [Usaco2007 Feb]Building A New Barn新牛舍 数学

    题意:链接 方法:数学+模拟 解析: 首先这类问题不是第一次见了,所以直接知道拿x的中位数.y的中位数. 这题就是讨论情况很的烦. 题中有个限制,给出待求和的点不能选取. 所以假设奇数个点,求出x中位 ...

  5. PHP中字符串比较的常用方法

    PHP中字符串比较的常用方法 一.总结 1.其实应该是直接等于号就可以了的 2.也可用strcmp,注意返回值 二.PHP中字符串比较的常用方法 1.按字节比较 按字节比较字符串是最常用的方法.其中可 ...

  6. HTML5的设计目的是为了在移动设备上支持多媒体

    HTML5的设计目的是为了在移动设备上支持多媒体

  7. JAVA MessageDigest(MD5加密等)

    转自http://blog.csdn.net/hudashi/article/details/8394158 一.概述 java.security.MessageDigest类用于为应用程序提供信息摘 ...

  8. VB 宏+mysql解决EXCEL表格实现自动化处理

    1.表格模板自动建立源码 Sub opp()Dim myPath$, myFile$, AK As WorkbookApplication.ScreenUpdating = FalsemyPath = ...

  9. Direct2D 如何关闭抗锯齿

    // Each pixel is rendered if its pixel center is contained by the geometry. // D2D1_ANTIALIAS_MODE_A ...

  10. VPS的centOS6安装远程桌面

    VPS的centOS6安装远程桌面 64位系统的需要编译安装 ttp://www.landui.com/help/Show-991.html xrdp是在图形界面下使用的,首先要确定您的centos系 ...