關於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 ([email protected]) ***/
- 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 ([email protected]) ***/
- 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多種途徑和簡單解釋