关于spring获取webApplication.getBean多种途径和简单解释
-
ApplicationContext ac1 = new FileSystemXmlApplicationContext("com/spark/system/applicationContext.xml");//如果配置文件放在文件系统的目录下则优先使用该方式
-
//com/spark/system/applicationContext.xml等价于"file:com/spark/system/applicationContext.xml"
-
ac1.getBean("beanId");
-
-
//ApplicationContext ac2=new ClassPathXmlApplicationContext("com/spark/system/applicationContext.xml");//如果配置文件在类路径下则优先使用该方式
-
//com/spark/system/applicationContext.xml 等价于"classpath:com/spark/system/applicationContext.xml"
-
ac2.getBean("beanId");
-
说明:
这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。
-
public void getBean(HttpServletRequest req,HttpSession se)
-
{
-
// se.getServletContext() 也可以
-
WebApplicationContext wac=(WebApplicationContext)req.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
-
wac.getBean("");
-
}
说明:此种方式正是我们下面所提到的WebApplicationContextUtils 工具类中getWebApplicationContext(ServletContext sc) 方法的内部实现,以下方式是通过spring 提供的WebApplicationContextUtils 工具类获取WebApplicationContext
方式一:
-
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。
方式二:
-
import org.springframework.web.context.WebApplicationContext;
-
import org.springframework.web.context.support.WebApplicationObjectSupport;
-
-
public class ApplicationContextUtils extends WebApplicationObjectSupport{
-
-
public WebApplicationContext isgetWebApplicationContext(){
-
return super.getWebApplicationContext();
-
}
-
-
}
继承自抽象类WebApplicationObjectSupport
说明:
抽象类WebApplicationObjectSupport 继承自ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该ApplicationObjectSupport 的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。当然直接继承ApplicationObjectSupport自己实现也可以,既然spring
提供了更方便的抽象工具类WebApplicationObjectSupport 建议使用它。以免出现问题
下面看WebApplicationObjectSupport关键源码(红色部分)
-
/*** Eclipse Class Decompiler, copyright (c) 2012 cnfree (cnfree2000@hotmail.com) ***/
-
package org.springframework.web.context.support;
-
-
import java.io.File;
-
import javax.servlet.ServletContext;
-
import org.springframework.context.ApplicationContext;
-
import org.springframework.context.support.ApplicationObjectSupport;
-
import org.springframework.web.context.ServletContextAware;
-
import org.springframework.web.context.WebApplicationContext;
-
import org.springframework.web.util.WebUtils;
-
-
public abstract class WebApplicationObjectSupport <span style="color:#FF0000;">extends ApplicationObjectSupport</span> implements ServletContextAware{
-
-
private ServletContext servletContext;
-
-
public final void setServletContext(ServletContext servletContext){
-
if (servletContext != this.servletContext){
-
this.servletContext = servletContext;
-
if (servletContext != null) initServletContext(servletContext);
-
}
-
}
-
-
protected boolean isContextRequired(){
-
return true;
-
}
-
-
protected void initApplicationContext(ApplicationContext context){
-
super.initApplicationContext(context);
-
if ((this.servletContext == null)
-
&& (context instanceof WebApplicationContext)){
-
this.servletContext = ((WebApplicationContext)context)
-
.getServletContext();
-
if (this.servletContext != null)
-
initServletContext(this.servletContext);
-
}
-
}
-
-
protected void initServletContext(ServletContext servletContext){}
-
-
<span style="color:#FF0000;">protected final WebApplicationContext getWebApplicationContext()
-
throws IllegalStateException{
-
ApplicationContext ctx = getApplicationContext();
-
if (ctx instanceof WebApplicationContext){ return ((WebApplicationContext)getApplicationContext()); }
-
if (isContextRequired()){ throw new IllegalStateException(
-
"WebApplicationObjectSupport instance [" + this
-
+ "] does not run in a WebApplicationContext but in: "
-
+ ctx); }
-
return null;
-
}</span>
-
-
protected final ServletContext getServletContext()
-
throws IllegalStateException{
-
if (this.servletContext != null){ return this.servletContext; }
-
ServletContext servletContext = getWebApplicationContext()
-
.getServletContext();
-
if ((servletContext == null) && (isContextRequired())){ throw new IllegalStateException(
-
"WebApplicationObjectSupport instance ["
-
+ this
-
+ "] does not run within a ServletContext. Make sure the object is fully configured!"); }
-
return servletContext;
-
}
-
-
protected final File getTempDir() throws IllegalStateException{
-
return WebUtils.getTempDir(getServletContext());
-
}
-
}
下面是ApplicationObjectSupport源码
-
/*** Eclipse Class Decompiler, copyright (c) 2012 cnfree (cnfree2000@hotmail.com) ***/
-
package org.springframework.context.support;
-
-
import org.apache.commons.logging.Log;
-
import org.apache.commons.logging.LogFactory;
-
import org.springframework.beans.BeansException;
-
import org.springframework.context.ApplicationContext;
-
import org.springframework.context.ApplicationContextAware;
-
import org.springframework.context.ApplicationContextException;
-
-
public abstract class ApplicationObjectSupport implements
-
ApplicationContextAware{
-
-
protected final Log logger;
-
-
private ApplicationContext applicationContext;
-
-
private MessageSourceAccessor messageSourceAccessor;
-
-
public ApplicationObjectSupport(){
-
this.logger = LogFactory.getLog(super.getClass());
-
}
-
-
public final void setApplicationContext(ApplicationContext context)
-
throws BeansException{
-
if ((context == null) && (!(isContextRequired()))){
-
this.applicationContext = null;
-
this.messageSourceAccessor = null;
-
}
-
else if (this.applicationContext == null){
-
if (!(requiredContextClass().isInstance(context))){ throw new ApplicationContextException(
-
"Invalid application context: needs to be of type ["
-
+ requiredContextClass().getName() + "]"); }
-
this.applicationContext = context;
-
this.messageSourceAccessor = new MessageSourceAccessor(context);
-
initApplicationContext(context);
-
}
-
else if (this.applicationContext != context){ throw new ApplicationContextException(
-
"Cannot reinitialize with different application context: current one is ["
-
+ this.applicationContext + "], passed-in one is ["
-
+ context + "]"); }
-
}
-
-
protected boolean isContextRequired(){
-
return false;
-
}
-
-
protected Class requiredContextClass(){
-
return ApplicationContext.class;
-
}
-
-
protected void initApplicationContext(ApplicationContext context)
-
throws BeansException{
-
initApplicationContext();
-
}
-
-
protected void initApplicationContext() throws BeansException{}
-
-
public final ApplicationContext getApplicationContext()
-
throws IllegalStateException{
-
if ((this.applicationContext == null) && (isContextRequired())){ throw new IllegalStateException(
-
"ApplicationObjectSupport instance [" + this
-
+ "] does not run in an ApplicationContext"); }
-
return this.applicationContext;
-
}
-
-
protected final MessageSourceAccessor getMessageSourceAccessor()
-
throws IllegalStateException{
-
if ((this.messageSourceAccessor == null) && (isContextRequired())){ throw new IllegalStateException(
-
"ApplicationObjectSupport instance [" + this
-
+ "] does not run in an ApplicationContext"); }
-
return this.messageSourceAccessor;
-
}
-
}
通过源码很容易看得出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 实例
例如:
-
ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
-
Resource resource=resolver.getResource("classpath:com/**/beans.xml");
-
BeanFactory bf=new XmlBeanFactory(resource);
-
bf.getBean("beanId");
有待研究 通过BeanFactory.getBean和ApplicationContext.getBean 的异同解释,和利弊以及使用情况。志同道合的同志可随时留言讨论,小弟欢迎大家一起学习
本文属于原创,请勿抄袭,谢谢!
关于spring获取webApplication.getBean多种途径和简单解释的更多相关文章
- paip.spring 获取bean getBean 没有beanid的情况下
paip.spring 获取bean getBean 没有beanid的情况下 spring能自动扫描带有注解的bean文件.. 作者Attilax 艾龙, EMAIL:1466519819@q ...
- Spring学习总结(一)——Spring实现IoC的多种方式
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法.没有IoC的程序中我们使用面向对象编程对象的创 ...
- spring获取webapplicationcontext,applicationcontext几种方法详解
法一:在初始化时保存ApplicationContext对象代码: ApplicationContext ac = new FileSystemXmlApplicationContext(" ...
- Spring实现Ioc的多种方式--控制反转、依赖注入、xml配置的方式实现IoC、对象作用域
Spring实现Ioc的多种方式 一.IoC基础 1.1.概念: 1.IoC 控制反转(Inversion of Control) IoC是一种设计思想. 2.DI 依赖注入 依赖注入是实现IoC的一 ...
- spring获取webapplicationcontext,applicationcontext几种方法详解(转)
方法一:在初始化时保存ApplicationContext对象 代码: ApplicationContext ac = new FileSystemXmlApplicationContext(&quo ...
- spring获取webapplicationcontext,applicationcontext几种方法详解(转载)
转载自 http://www.blogjava.net/Todd/archive/2010/04/22/295112.html 方法一:在初始化时保存ApplicationContext对象 代码: ...
- spring 获取 WebApplicationContext的几种方法
spring 获取 WebApplicationContext的几种方法 使用ContextLoader WebApplicationContext webApplicationContext = C ...
- Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式
转自:http://chinazhaokeke.blog.163.com/blog/static/109409055201092811354236 Spring获取ApplicationContex ...
- spring获取bean的时候严格区分大小写
如题:spring获取bean的时候严格区分大小写 配置文件helloservice.xml中配置: <dubbo:reference id="IInsurance" int ...
随机推荐
- POJ 1061 青蛙的约会 数论水题
http://poj.org/problem?id=1061 傻逼题不多说 (x+km) - (y+kn) = dL 求k 令b = n-m ; a = x - y ; 化成模线性方程一般式 : Lx ...
- Kali linux查看局域网内其他用户的输入信息
使用nmap 工具在局域网里进行侦探,查看局域网里ip存活数量 root@kali:~# nmap -sP 192.168.1.0/24 Starting Nmap 7.60 ( https://nm ...
- yum---rpm软件包管理器
yum命令是在Fedora和RedHat以及SUSE中基于rpm的软件包管理器,它可以使系统管理人员交互和自动化地更细与管理RPM软件包,能够从指定的服务器自动下载RPM包并且安装,可以自动处理依赖性 ...
- linux新安装后root密码设置
linux在安装过程中未设置root密码 导致在使用中无法su 解决方法是设置root密码: 输入: sudo passwd root [sudo] password for you: ---> ...
- apache wicket 7.X之HelloWorld
Wicket是什么 Wicket一个开发Java Web应用程序框架. 它使得开发web应用程序变得easy而轻松. Wicket利用一个POJO data beans组件使得它能够与不论什么持久层技 ...
- cocos2dx-js学习笔记(一)环境搭建
本人眼下的学习方向是cocos2dx+js的开发方式,开发调试使用webstrom和火狐浏览器,调试完毕的项目使用cocos2dx+jsb的方式编译到PC或android设备执行.主要时间用在学习,所 ...
- lighttpd启动不了,libssl.so.4&libcrypto.so.4 缺失
lighttd的出错日志在 log/out_lighttpd 里,当lighttd启动不了时候,这里文件中会说明原因. 今天的报错是 error while loading shared librar ...
- web存储方法,现成代码
1.cookie的设置与取用 function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(e ...
- BZOJ4372: 烁烁的游戏(动态点分治)
Description 背景:烁烁很喜欢爬树,这吓坏了树上的皮皮鼠.题意:给定一颗n个节点的树,边权均为1,初始树上没有皮皮鼠.烁烁他每次会跳到一个节点u,把周围与他距离不超过d的节点各吸引出w只皮皮 ...
- 事件循环(Event Loop)
1.什么是事件循环? JavaScript为单线程执行的,所以是从上到下依次执行,js分为两个任务,宏任务和微任务 首先执行宏任务(第一次就是执行所有的同步代码),再执行所有的微任务,执行完毕之后再次 ...