关于spring获取webApplication.getBean多种途径和简单解释

  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.   
  5. //ApplicationContext ac2=new ClassPathXmlApplicationContext("com/spark/system/applicationContext.xml");//如果配置文件在类路径下则优先使用该方式  
  6. //com/spark/system/applicationContext.xml 等价于"classpath:com/spark/system/applicationContext.xml"  
  7.  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.   
  4. public class ApplicationContextUtils extends WebApplicationObjectSupport{  
  5.   
  6.     public  WebApplicationContext isgetWebApplicationContext(){  
  7.         return super.getWebApplicationContext();  
  8.     }  
  9.       
  10. }  


继承自抽象类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.   
  4. import java.io.File;  
  5. import javax.servlet.ServletContext;  
  6. import org.springframework.context.ApplicationContext;  
  7. import org.springframework.context.support.ApplicationObjectSupport;  
  8. import org.springframework.web.context.ServletContextAware;  
  9. import org.springframework.web.context.WebApplicationContext;  
  10. import org.springframework.web.util.WebUtils;  
  11.   
  12. public abstract class WebApplicationObjectSupport <span style="color:#FF0000;">extends ApplicationObjectSupport</span> implements ServletContextAware{  
  13.   
  14.     private ServletContext servletContext;  
  15.   
  16.     public final void setServletContext(ServletContext servletContext){  
  17.         if (servletContext != this.servletContext){  
  18.             this.servletContext = servletContext;  
  19.             if (servletContext != null) initServletContext(servletContext);  
  20.         }  
  21.     }  
  22.   
  23.     protected boolean isContextRequired(){  
  24.         return true;  
  25.     }  
  26.   
  27.     protected void initApplicationContext(ApplicationContext context){  
  28.         super.initApplicationContext(context);  
  29.         if ((this.servletContext == null)  
  30.                 && (context instanceof WebApplicationContext)){  
  31.             this.servletContext = ((WebApplicationContext)context)  
  32.                     .getServletContext();  
  33.             if (this.servletContext != null)  
  34.                 initServletContext(this.servletContext);  
  35.         }  
  36.     }  
  37.   
  38.     protected void initServletContext(ServletContext servletContext){}  
  39.   
  40.     <span style="color:#FF0000;">protected final WebApplicationContext getWebApplicationContext()  
  41.             throws IllegalStateException{  
  42.         ApplicationContext ctx = getApplicationContext();  
  43.         if (ctx instanceof WebApplicationContext){ return ((WebApplicationContext)getApplicationContext()); }  
  44.         if (isContextRequired()){ throw new IllegalStateException(  
  45.                 "WebApplicationObjectSupport instance [" + this  
  46.                         + "] does not run in a WebApplicationContext but in: "  
  47.                         + ctx); }  
  48.         return null;  
  49.     }</span>  
  50.   
  51.     protected final ServletContext getServletContext()  
  52.             throws IllegalStateException{  
  53.         if (this.servletContext != null){ return this.servletContext; }  
  54.         ServletContext servletContext = getWebApplicationContext()  
  55.                 .getServletContext();  
  56.         if ((servletContext == null) && (isContextRequired())){ throw new IllegalStateException(  
  57.                 "WebApplicationObjectSupport instance ["  
  58.                         + this  
  59.                         + "] does not run within a ServletContext. Make sure the object is fully configured!"); }  
  60.         return servletContext;  
  61.     }  
  62.   
  63.     protected final File getTempDir() throws IllegalStateException{  
  64.         return WebUtils.getTempDir(getServletContext());  
  65.     }  
  66. }  

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

通过源码很容易看得出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"); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值