`
gstarwd
  • 浏览: 1524925 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Spring源码分析-配置文件加载流程

阅读更多

Spring配置文件加载流程

Spring配置文件是集成了Spring框架的项目的核心,引擎从哪里开始,中间都执行了哪些操作,小谈一下它的执行流程。

容器先是加载web .xml

 

接着是applicationContext.xml在web .xml里的注册

 

一种方法是加入ContextLoaderServlet这个servlet

Xml代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://silmon.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3Ccontext-param%3E%0A%09%09%3Cparam-name%3EcontextConfigLocation%3C%2Fparam-name%3E%0A%09%09%3Cparam-value%3E%2FWEB-INF%2FapplicationContext.xml%3C%2Fparam-value%3E%0A%09%3C%2Fcontext-param%3E%0A%20%20%20%20%20%3Cservlet%3E%0A%09%09%3Cservlet-name%3Econtext%3C%2Fservlet-name%3E%0A%09%09%3Cservlet-class%3E%0A%09%09%09org.springframework.web.context.ContextLoaderServlet%0A%09%09%3C%2Fservlet-class%3E%0A%09%09%3Cload-on-startup%3E0%3C%2Fload-on-startup%3E%0A%09%3C%2Fservlet%3E" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. < context-param >   
  2.         < param-name > contextConfigLocation </ param-name >   
  3.         < param-value > /WEB -INF/applicationContext.xml </ param-value >   
  4.     </ context-param >   
  5.      < servlet >   
  6.         < servlet-name > context </ servlet-name >   
  7.         < servlet-class >   
  8.             org.springframework.web .context.ContextLoaderServlet  
  9.         </ servlet-class >   
  10.         < load-on-startup > 0 </ load-on-startup >   
  11.     </ servlet >   
<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB
-INF/applicationContext.xml</param-value>
	</context-param>
     <servlet>
		<servlet-name>context</servlet-name>
		<servlet-class>
			org.springframework.web
.context.ContextLoaderServlet
		</servlet-class>
		<load-on-startup>0</load-on-startup>
	</servlet>

还有一种是添加ContextLoaderListener这个监听器

Xml代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://silmon.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3Ccontext-param%3E%0A%20%20%20%20%3Cparam-name%3EcontextConfigLocation%3C%2Fparam-name%3E%0A%20%20%20%20%3Cparam-value%3E%2FWEB-INF%2FapplicationContext.xml%3C%2Fparam-value%3E%0A%3C%2Fcontext-param%3E%0A%0A%3Clistener%3E%0A%20%20%20%20%3Clistener-class%3Eorg.springframework.web.context.ContextLoaderListener%3C%2Flistener-class%3E%0A%3C%2Flistener%3E" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. < context-param >   
  2.     < param-name > contextConfigLocation </ param-name >   
  3.     < param-value > /WEB -INF/applicationContext.xml </ param-value >   
  4. </ context-param >   
  5.   
  6. < listener >   
  7.     < listener-class > org.springframework.web .context.ContextLoaderListener </ listener-class >   
  8. </ listener >   
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB
-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web
.context.ContextLoaderListener</listener-class>
</listener>
 

 

下面是ContextLoaderServlet源代码

Java代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://silmon.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=package%20org.springframework.web.context%3B%0A%0Aimport%20java.io.IOException%3B%0A%0Aimport%20javax.servlet.ServletException%3B%0Aimport%20javax.servlet.http.HttpServlet%3B%0Aimport%20javax.servlet.http.HttpServletRequest%3B%0Aimport%20javax.servlet.http.HttpServletResponse%3B%0A%0Apublic%20class%20ContextLoaderServlet%20extends%20HttpServlet%20%7B%0A%0A%09private%20ContextLoader%20contextLoader%3B%0A%0A%0A%09%2F**%0A%09%20*%20Initialize%20the%20root%20web%20application%20context.%0A%09%20*%2F%0A%0Apublic%20void%20init()%20throws%20ServletException%20%7B%0A%09%09this.contextLoader%20%3D%20createContextLoader()%3B%0A%09%09this.contextLoader.initWebApplicationContext(getServletContext())%3B%0A%09%7D%09%2F**%0A%09%20*%20Create%20the%20ContextLoader%20to%20use.%20Can%20be%20overridden%20in%20subclasses.%0A%09%20*%20%40return%20the%20new%20ContextLoader%0A%09%20*%2F%0A%09protected%20ContextLoader%20createContextLoader()%20%7B%0A%09%09return%20new%20ContextLoader()%3B%0A%09%7D%0A%0A%09%2F**%0A%09%20*%20Return%20the%20ContextLoader%20used%20by%20this%20servlet.%20%0A%09%20*%20%40return%20the%20current%20ContextLoader%0A%09%20*%2F%0A%09public%20ContextLoader%20getContextLoader()%20%7B%0A%09%09return%20this.contextLoader%3B%0A%09%7D%0A%0A%0A%09%2F**%0A%09%20*%20Close%20the%20root%20web%20application%20context.%0A%09%20*%2F%0A%09public%20void%20destroy()%20%7B%0A%09%09if%20(this.contextLoader%20!%3D%20null)%20%7B%0A%09%09%09this.contextLoader.closeWebApplicationContext(getServletContext())%3B%0A%09%09%7D%0A%09%7D%0A%0A%0A%09%2F**%0A%09%20*%20This%20should%20never%20even%20be%20called%20since%20no%20mapping%20to%20this%20servlet%20should%0A%09%20*%20ever%20be%20created%20in%20web.xml.%20That's%20why%20a%20correctly%20invoked%20Servlet%202.3%0A%09%20*%20listener%20is%20much%20more%20appropriate%20for%20initialization%20work%20%3B-)%0A%09%20*%2F%0A%09public%20void%20service(HttpServletRequest%20request%2C%20HttpServletResponse%20response)%20throws%20IOException%20%7B%0A%09%09getServletContext().log(%0A%09%09%09%09%22Attempt%20to%20call%20service%20method%20on%20ContextLoaderServlet%20as%20%5B%22%20%2B%0A%09%09%09%09request.getRequestURI()%20%2B%20%22%5D%20was%20ignored%22)%3B%0A%09%09response.sendError(HttpServletResponse.SC_BAD_REQUEST)%3B%0A%09%7D%0A%0A%0A%09public%20String%20getServletInfo()%20%7B%0A%09%09return%20%22ContextLoaderServlet%20for%20Servlet%20API%202.3%20%22%20%2B%0A%09%09%20%20%20%20%22(deprecated%20in%20favor%20of%20ContextLoaderListener%20for%20Servlet%20API%202.4)%22%3B%0A%09%7D%0A%0A%7D" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. package  org.springframework.web .context;  
  2.   
  3. import  java.io.IOException;  
  4.   
  5. import  javax.servlet.ServletException;  
  6. import  javax.servlet.http.HttpServlet;  
  7. import  javax.servlet.http.HttpServletRequest;  
  8. import  javax.servlet.http.HttpServletResponse;  
  9.   
  10. public   class  ContextLoaderServlet  extends  HttpServlet {  
  11.   
  12.     private  ContextLoader  contextLoader ;  
  13.   
  14.   
  15.     /**  
  16.      * Initialize the root web  application context.  
  17.      */   
  18.   
  19. public   void  init()  throws  ServletException {  
  20.         this .contextLoader  = createContextLoader();  
  21.         this .contextLoader .initWebApplicationContext(getServletContext());  
  22.     }   /**  
  23.      * Create the ContextLoader  to use. Can be overridden in  subclasses.  
  24.      * @return the new ContextLoader  
  25.      */   
  26.     protected  ContextLoader  createContextLoader() {  
  27.         return   new  ContextLoader ();  
  28.     }  
  29.   
  30.     /**  
  31.      * Return the ContextLoader  used by this servlet.   
  32.      * @return the current ContextLoader  
  33.      */   
  34.     public  ContextLoader  getContextLoader() {  
  35.         return   this .contextLoader ;  
  36.     }  
  37.   
  38.   
  39.     /**  
  40.      * Close the root web  application context.  
  41.      */   
  42.     public   void  destroy() {  
  43.         if  ( this .contextLoader  !=  null ) {  
  44.             this .contextLoader .closeWebApplicationContext(getServletContext());  
  45.         }  
  46.     }  
  47.   
  48.   
  49.     /**  
  50.      * This should never even be called since no mapping to this servlet should  
  51.      * ever be created in  web .xml. That's why a correctly invoked Servlet 2.3  
  52.      * listener is much more appropriate for initialization work ;-)  
  53.      */   
  54.     public   void  service(HttpServletRequest request, HttpServletResponse response)  throws  IOException {  
  55.         getServletContext().log(  
  56.                 "Attempt to call service method on ContextLoaderServlet as ["  +  
  57.                 request.getRequestURI() + "] was ignored" );  
  58.         response.sendError(HttpServletResponse.SC_BAD_REQUEST);  
  59.     }  
  60.   
  61.   
  62.     public  String getServletInfo() {  
  63.         return   "ContextLoaderServlet for Servlet API 2.3 "  +  
  64.             "(deprecated in  favor of ContextLoaderListener for Servlet API 2.4)" ;  
  65.     }  
  66.   
  67. }  
package org.springframework.web
.context;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContextLoaderServlet extends HttpServlet {

	private ContextLoader
 contextLoader
;


	/**
	 * Initialize the root web
 application context.
	 */

public void init() throws ServletException {
		this.contextLoader
 = createContextLoader();
		this.contextLoader
.initWebApplicationContext(getServletContext());
	}	/**
	 * Create the ContextLoader
 to use. Can be overridden in
 subclasses.
	 * @return the new ContextLoader

	 */
	protected ContextLoader
 createContextLoader() {
		return new ContextLoader
();
	}

	/**
	 * Return the ContextLoader
 used by this servlet. 
	 * @return the current ContextLoader

	 */
	public ContextLoader
 getContextLoader() {
		return this.contextLoader
;
	}


	/**
	 * Close the root web
 application context.
	 */
	public void destroy() {
		if (this.contextLoader
 != null) {
			this.contextLoader
.closeWebApplicationContext(getServletContext());
		}
	}


	/**
	 * This should never even be called since no mapping to this servlet should
	 * ever be created in
 web
.xml. That's why a correctly invoked Servlet 2.3
	 * listener is much more appropriate for initialization work ;-)
	 */
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
		getServletContext().log(
				"Attempt to call service method on ContextLoaderServlet as [" +
				request.getRequestURI() + "] was ignored");
		response.sendError(HttpServletResponse.SC_BAD_REQUEST);
	}


	public String getServletInfo() {
		return "ContextLoaderServlet for Servlet API 2.3 " +
		    "(deprecated in
 favor of ContextLoaderListener for Servlet API 2.4)";
	}

}
 

ContextLoaderListener源代码

Java代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://silmon.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=package%20org.springframework.web.context%3B%0A%0Aimport%20javax.servlet.ServletContextEvent%3B%0Aimport%20javax.servlet.ServletContextListener%3B%0A%0Apublic%20class%20ContextLoaderListener%20implements%20ServletContextListener%20%7B%0A%0A%09private%20ContextLoader%20contextLoader%3B%0A%0A%0A%09%2F**%0A%09%20*%20Initialize%20the%20root%20web%20application%20context.%0A%09%20*%2F%0A%09public%20void%20contextInitialized(ServletContextEvent%20event)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20this.contextLoader%20%3D%20createContextLoader()%3B%0A%09%09this.contextLoader.initWebApplicationContext(event.getServletContext())%3B%0A%09%7D%0A%0A%09%2F**%0A%09%20*%20Create%20the%20ContextLoader%20to%20use.%20Can%20be%20overridden%20in%20subclasses.%0A%09%20*%20%40return%20the%20new%20ContextLoader%0A%09%20*%2F%0A%09protected%20ContextLoader%20createContextLoader()%20%7B%0A%09%09return%20new%20ContextLoader()%3B%0A%09%7D%0A%0A%09%2F**%0A%09%20*%20Return%20the%20ContextLoader%20used%20by%20this%20listener.%0A%09%20*%20%40return%20the%20current%20ContextLoader%0A%09%20*%2F%0A%09public%20ContextLoader%20getContextLoader()%20%7B%0A%09%09return%20this.contextLoader%3B%0A%09%7D%0A%0A%0A%09%2F**%0A%09%20*%20Close%20the%20root%20web%20application%20context.%0A%09%20*%2F%0A%09public%20void%20contextDestroyed(ServletContextEvent%20event)%20%7B%0A%09%09if%20(this.contextLoader%20!%3D%20null)%20%7B%0A%09%09%09this.contextLoader.closeWebApplicationContext(event.getServletContext())%3B%0A%09%09%7D%0A%09%7D%0A%0A%7D%0A" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. package  org.springframework.web .context;  
  2.   
  3. import  javax.servlet.ServletContextEvent;  
  4. import  javax.servlet.ServletContextListener;  
  5.   
  6. public   class  ContextLoaderListener  implements  ServletContextListener {  
  7.   
  8.     private  ContextLoader  contextLoader ;  
  9.   
  10.   
  11.     /**  
  12.      * Initialize the root web  application context.  
  13.      */   
  14.     public   void  contextInitialized(ServletContextEvent event) {  
  15.                this .contextLoader  = createContextLoader();  
  16.         this .contextLoader .initWebApplicationContext(event.getServletContext());  
  17.     }  
  18.   
  19.     /**  
  20.      * Create the ContextLoader  to use. Can be overridden in  subclasses.  
  21.      * @return the new ContextLoader  
  22.      */   
  23.     protected  ContextLoader  createContextLoader() {  
  24.         return   new  ContextLoader ();  
  25.     }  
  26.   
  27.     /**  
  28.      * Return the ContextLoader  used by this listener.  
  29.      * @return the current ContextLoader  
  30.      */   
  31.     public  ContextLoader  getContextLoader() {  
  32.         return   this .contextLoader ;  
  33.     }  
  34.   
  35.   
  36.     /**  
  37.      * Close the root web  application context.  
  38.      */   
  39.     public   void  contextDestroyed(ServletContextEvent event) {  
  40.         if  ( this .contextLoader  !=  null ) {  
  41.             this .contextLoader .closeWebApplicationContext(event.getServletContext());  
  42.         }  
  43.     }  
  44.   
  45. }  
package org.springframework.web
.context;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextLoaderListener implements ServletContextListener {

	private ContextLoader
 contextLoader
;


	/**
	 * Initialize the root web
 application context.
	 */
	public void contextInitialized(ServletContextEvent event) {
               this.contextLoader
 = createContextLoader();
		this.contextLoader
.initWebApplicationContext(event.getServletContext());
	}

	/**
	 * Create the ContextLoader
 to use. Can be overridden in
 subclasses.
	 * @return the new ContextLoader

	 */
	protected ContextLoader
 createContextLoader() {
		return new ContextLoader
();
	}

	/**
	 * Return the ContextLoader
 used by this listener.
	 * @return the current ContextLoader

	 */
	public ContextLoader
 getContextLoader() {
		return this.contextLoader
;
	}


	/**
	 * Close the root web
 application context.
	 */
	public void contextDestroyed(ServletContextEvent event) {
		if (this.contextLoader
 != null) {
			this.contextLoader
.closeWebApplicationContext(event.getServletContext());
		}
	}

}

 以上都提到了ContextLoader 这个类

Java代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://silmon.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=package%20org.springframework.web.context%3B%0A%0Apublic%20class%20ContextLoader%20%7B%0A%0A%09public%20static%20final%20String%20CONTEXT_CLASS_PARAM%20%3D%20%22contextClass%22%3B%0A%0A%09public%20static%20final%20String%20CONFIG_LOCATION_PARAM%20%3D%20%22contextConfigLocation%22%3B%0A%0A%20%20%20%20%20%20%20public%20static%20final%20String%20LOCATOR_FACTORY_SELECTOR_PARAM%20%3D%20%22locatorFactorySelector%22%3B%0A%0A%09public%20static%20final%20String%20LOCATOR_FACTORY_KEY_PARAM%20%3D%20%22parentContextKey%22%3B%0A%0A%09private%20static%20final%20String%20DEFAULT_STRATEGIES_PATH%20%3D%20%22ContextLoader.properties%22%3B%0A%0A%0A%09private%20static%20final%20Properties%20defaultStrategies%3B%0A%0A%09static%20%7B%0A%09%09%09%09try%20%7B%0A%09%09%09ClassPathResource%20resource%20%3D%20new%20ClassPathResource(DEFAULT_STRATEGIES_PATH%2C%20ContextLoader.class)%3B%0A%09%09%09defaultStrategies%20%3D%20PropertiesLoaderUtils.loadProperties(resource)%3B%0A%09%09%7D%0A%09%09catch%20(IOException%20ex)%20%7B%0A%09%09%09throw%20new%20IllegalStateException(%22Could%20not%20load%20'ContextLoader.properties'%3A%20%22%20%2B%20ex.getMessage())%3B%0A%09%09%7D%0A%09%7D%0A%0A%0A%09private%20static%20final%20Log%20logger%20%3D%20LogFactory.getLog(ContextLoader.class)%3B%0A%0A%09private%20static%20final%20Map%20currentContextPerThread%20%3D%20CollectionFactory.createConcurrentMapIfPossible(1)%3B%0A%0A%09private%20WebApplicationContext%20context%3B%0A%0A%09private%20BeanFactoryReference%20parentContextRef%3B%0A%0A%09public%20WebApplicationContext%20initWebApplicationContext(ServletContext%20servletContext)%0A%0A%20%20%20%20%20%20%20%20%20%20throws%20IllegalStateException%2C%20BeansException%20%7B%0A%0A%09%09if%20(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)%20!%3D%20null)%20%7B%0A%09%09%09throw%20new%20IllegalStateException(%0A%09%09%09%09%09%22Cannot%20initialize%20context%20because%20there%20is%20already%20a%20root%20application%20context%20present%20-%20%22%20%2B%0A%09%09%09%09%09%22check%20whether%20you%20have%20multiple%20ContextLoader*%20definitions%20in%20your%20web.xml!%22)%3B%0A%09%09%7D%0A%0A%09%09servletContext.log(%22Initializing%20Spring%20root%20WebApplicationContext%22)%3B%0A%09%09if%20(logger.isInfoEnabled())%20%7B%0A%09%09%09logger.info(%22Root%20WebApplicationContext%3A%20initialization%20started%22)%3B%0A%09%09%7D%0A%09%09long%20startTime%20%3D%20System.currentTimeMillis()%3B%0A%0A%09%09try%20%7B%0A%09%09%09%2F%2F%20Determine%20parent%20for%20root%20web%20application%20context%2C%20if%20any.%0A%09%09%09ApplicationContext%20parent%20%3D%20loadParentContext(servletContext)%3B%0A%0A%09%09%09%2F%2F%20Store%20context%20in%20local%20instance%20variable%2C%20to%20guarantee%20that%0A%09%09%09%2F%2F%20it%20is%20available%20on%20ServletContext%20shutdown.%0A%09%09%09this.context%20%3D%20createWebApplicationContext(servletContext%2C%20parent)%3B%0A%09%09%09servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE%2C%20this.context)%3B%0A%09%09%09currentContextPerThread.put(Thread.currentThread().getContextClassLoader()%2C%20this.context)%3B%0A%0A%09%09%09if%20(logger.isDebugEnabled())%20%7B%0A%09%09%09%09logger.debug(%22Published%20root%20WebApplicationContext%20as%20ServletContext%20attribute%20with%20name%20%5B%22%20%2B%0A%09%09%09%09%09%09WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE%20%2B%20%22%5D%22)%3B%0A%09%09%09%7D%0A%09%09%09if%20(logger.isInfoEnabled())%20%7B%0A%09%09%09%09long%20elapsedTime%20%3D%20System.currentTimeMillis()%20-%20startTime%3B%0A%09%09%09%09logger.info(%22Root%20WebApplicationContext%3A%20initialization%20completed%20in%20%22%20%2B%20elapsedTime%20%2B%20%22%20ms%22)%3B%0A%09%09%09%7D%0A%0A%09%09%09return%20this.context%3B%0A%09%09%7D%0A%09%09catch%20(RuntimeException%20ex)%20%7B%0A%09%09%09logger.error(%22Context%20initialization%20failed%22%2C%20ex)%3B%0A%09%09%09servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE%2C%20ex)%3B%0A%09%09%09throw%20ex%3B%0A%09%09%7D%0A%09%09catch%20(Error%20err)%20%7B%0A%09%09%09logger.error(%22Context%20initialization%20failed%22%2C%20err)%3B%0A%09%09%09servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE%2C%20err)%3B%0A%09%09%09throw%20err%3B%0A%09%09%7D%0A%09%7D%0A%0A%09protected%20WebApplicationContext%20createWebApplicationContext(%0A%09%09%09ServletContext%20servletContext%2C%20ApplicationContext%20parent)%20throws%20BeansException%20%7B%0A%0A%09%09Class%20contextClass%20%3D%20determineContextClass(servletContext)%3B%0A%09%09if%20(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass))%20%7B%0A%09%09%09throw%20new%20ApplicationContextException(%22Custom%20context%20class%20%5B%22%20%2B%20contextClass.getName()%20%2B%0A%09%09%09%09%09%22%5D%20is%20not%20of%20type%20%5B%22%20%2B%20ConfigurableWebApplicationContext.class.getName()%20%2B%20%22%5D%22)%3B%0A%09%09%7D%0A%0A%09%09ConfigurableWebApplicationContext%20wac%20%3D%0A%09%09%09%09(ConfigurableWebApplicationContext)%20BeanUtils.instantiateClass(contextClass)%3B%0A%09%09wac.setParent(parent)%3B%0A%09%09wac.setServletContext(servletContext)%3B%0A%09%09%3Cspan%20style%3D%22color%3A%20rgb(0%2C%200%2C%200)%3B%22%3Ewac.setConfigLocation(servletContext.getInitParameter(CONFIG_LOCATION_PARAM))%3B%3C%2Fspan%3E%0A%0A%0A%0A%0A%0A%0AcustomizeContext(servletContext%2C%20wac)%3B%0A%09%09wac.refresh()%3B%0A%0A%09%09return%20wac%3B%0A%09%7D%0A%0A%09%09protected%20Class%20determineContextClass(ServletContext%20servletContext)%20throws%20ApplicationContextException%20%7B%0A%09%09String%20contextClassName%20%3D%20servletContext.getInitParameter(CONTEXT_CLASS_PARAM)%3B%0A%09%09if%20(contextClassName%20!%3D%20null)%20%7B%0A%09%09%09try%20%7B%0A%09%09%09%09return%20ClassUtils.forName(contextClassName)%3B%0A%09%09%09%7D%0A%09%09%09catch%20(ClassNotFoundException%20ex)%20%7B%0A%09%09%09%09throw%20new%20ApplicationContextException(%0A%09%09%09%09%09%09%22Failed%20to%20load%20custom%20context%20class%20%5B%22%20%2B%20contextClassName%20%2B%20%22%5D%22%2C%20ex)%3B%0A%09%09%09%7D%0A%09%09%7D%0A%09%09else%20%7B%0A%09%09%09contextClassName%20%3D%20defaultStrategies.getProperty(WebApplicationContext.class.getName())%3B%0A%09%09%09try%20%7B%0A%09%09%09%09return%20ClassUtils.forName(contextClassName%2C%20ContextLoader.class.getClassLoader())%3B%0A%09%09%09%7D%0A%09%09%09catch%20(ClassNotFoundException%20ex)%20%7B%0A%09%09%09%09throw%20new%20ApplicationContextException(%0A%09%09%09%09%09%09%22Failed%20to%20load%20default%20context%20class%20%5B%22%20%2B%20contextClassName%20%2B%20%22%5D%22%2C%20ex)%3B%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D%0A%0A%09%09protected%20void%20customizeContext(%0A%09%09%09ServletContext%20servletContext%2C%20ConfigurableWebApplicationContext%20applicationContext)%20%7B%0A%09%7D%0A%0A%09protected%20ApplicationContext%20loadParentContext(ServletContext%20servletContext)%0A%09%09%09throws%20BeansException%20%7B%0A%0A%09%09ApplicationContext%20parentContext%20%3D%20null%3B%0A%09%09String%20locatorFactorySelector%20%3D%20servletContext.getInitParameter(LOCATOR_FACTORY_SELECTOR_PARAM)%3B%0A%09%09String%20parentContextKey%20%3D%20servletContext.getInitParameter(LOCATOR_FACTORY_KEY_PARAM)%3B%0A%0A%09%09if%20(parentContextKey%20!%3D%20null)%20%7B%0A%09%09%09%2F%2F%20locatorFactorySelector%20may%20be%20null%2C%20indicating%20the%20default%20%22classpath*%3AbeanRefContext.xml%22%0A%09%09%09BeanFactoryLocator%20locator%20%3D%20ContextSingletonBeanFactoryLocator.getInstance(locatorFactorySelector)%3B%0A%09%09%09if%20(logger.isDebugEnabled())%20%7B%0A%09%09%09%09logger.debug(%22Getting%20parent%20context%20definition%3A%20using%20parent%20context%20key%20of%20'%22%20%2B%0A%09%09%09%09%09%09parentContextKey%20%2B%20%22'%20with%20BeanFactoryLocator%22)%3B%0A%09%09%09%7D%0A%09%09%09this.parentContextRef%20%3D%20locator.useBeanFactory(parentContextKey)%3B%0A%09%09%09parentContext%20%3D%20(ApplicationContext)%20this.parentContextRef.getFactory()%3B%0A%09%09%7D%0A%0A%09%09return%20parentContext%3B%0A%09%7D%0A%0A%09public%20void%20closeWebApplicationContext(ServletContext%20servletContext)%20%7B%0A%09%09servletContext.log(%22Closing%20Spring%20root%20WebApplicationContext%22)%3B%0A%09%09try%20%7B%0A%09%09%09if%20(this.context%20instanceof%20ConfigurableWebApplicationContext)%20%7B%0A%09%09%09%09((ConfigurableWebApplicationContext)%20this.context).close()%3B%0A%09%09%09%7D%0A%09%09%7D%0A%09%09finally%20%7B%0A%09%09%09currentContextPerThread.remove(Thread.currentThread().getContextClassLoader())%3B%0A%09%09%09servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)%3B%0A%09%09%09if%20(this.parentContextRef%20!%3D%20null)%20%7B%0A%09%09%09%09this.parentContextRef.release()%3B%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D%0A%0A%0A%09public%20static%20WebApplicationContext%20getCurrentWebApplicationContext()%20%7B%0A%09%09return%20(WebApplicationContext)%20currentContextPerThread.get(Thread.currentThread().getContextClassLoader())%3B%0A%09%7D%0A%0A%7D%0A" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. package  org.springframework.web .context;  
  2.   
  3. public   class  ContextLoader  {  
  4.   
  5.     public   static   final  String CONTEXT_CLASS_PARAM =  "contextClass" ;  
  6.   
  7.     public   static   final  String CONFIG_LOCATION_PARAM =  "contextConfigLocation" ;  
  8.   
  9.        public   static   final  String LOCATOR_FACTORY_SELECTOR_PARAM =  "locatorFactorySelector" ;  
  10.   
  11.     public   static   final  String LOCATOR_FACTORY_KEY_PARAM =  "parentContextKey" ;  
  12.   
  13.     private   static   final  String DEFAULT_STRATEGIES_PATH =  "ContextLoader .properties" ;  
  14.   
  15.   
  16.     private   static   final  Properties defaultStrategies;  
  17.   
  18.     static  {  
  19.                 try  {  
  20.             ClassPathResource resource = new  ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader . class );  
  21.             defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);  
  22.         }  
  23.         catch  (IOException ex) {  
  24.             throw   new  IllegalStateException( "Could not load 'ContextLoader .properties': "  + ex.getMessage());  
  25.         }  
  26.     }  
  27.   
  28.   
  29.     private   static   final  Log logger = LogFactory.getLog(ContextLoader . class );  
  30.   
  31.     private   static   final  Map currentContextPerThread = CollectionFactory.createConcurrentMapIfPossible( 1 );  
  32.   
  33.     private  WebApplicationContext context;  
  34.   
  35.     private  BeanFactoryReference parentContextRef;  
  36.   
  37.     public  WebApplicationContext initWebApplicationContext(ServletContext servletContext)  
  38.   
  39.           throws  IllegalStateException, BeansException {  
  40.   
  41.         if  (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) !=  null ) {  
  42.             throw   new  IllegalStateException(  
  43.                     "Cannot initialize context because there is already a root application context present - "  +  
  44.                     "check  whether  you  have  multiple  ContextLoaderdefinitions  in  your  web .xml!" );  
  45.         }  
  46.   
  47.         servletContext.log("Initializing Spring root WebApplicationContext" );  
  48.         if  (logger.isInfoEnabled()) {  
  49.             logger.info("Root WebApplicationContext: initialization started" );  
  50.         }  
  51.         long  startTime = System.currentTimeMillis();  
  52.   
  53.         try  {  
  54.             // Determine parent for root web  application context, if any.   
  55.             ApplicationContext parent = loadParentContext(servletContext);  
  56.   
  57.             // Store context in  local instance variable, to guarantee that   
  58.             // it is available on ServletContext shutdown.   
  59.             this .context = createWebApplicationContext(servletContext, parent);  
  60.             servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this .context);  
  61.             currentContextPerThread.put(Thread.currentThread().getContextClassLoader(), this .context);  
  62.   
  63.             if  (logger.isDebugEnabled()) {  
  64.                 logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["  +  
  65.                         WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]" );  
  66.             }  
  67.             if  (logger.isInfoEnabled()) {  
  68.                 long  elapsedTime = System.currentTimeMillis() - startTime;  
  69.                 logger.info("Root WebApplicationContext: initialization completed in  "  + elapsedTime +  " ms" );  
  70.             }  
  71.   
  72.             return   this .context;  
  73.         }  
  74.         catch  (RuntimeException ex) {  
  75.             logger.error("Context initialization failed" , ex);  
  76.             servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);  
  77.             throw  ex;  
  78.         }  
  79.         catch  (Error err) {  
  80.             logger.error("Context initialization failed" , err);  
  81.             servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);  
  82.             throw  err;  
  83.         }  
  84.     }  
  85.   
  86.     protected  WebApplicationContext createWebApplicationContext(  
  87.             ServletContext servletContext, ApplicationContext parent) throws  BeansException {  
  88.   
  89.         Class contextClass = determineContextClass(servletContext);  
  90.         if  (!ConfigurableWebApplicationContext. class .isAssignableFrom(contextClass)) {  
  91.             throw   new  ApplicationContextException( "Custom context class ["  + contextClass.getName() +  
  92.                     "] is not of type ["  + ConfigurableWebApplicationContext. class .getName() +  "]" );  
  93.         }  
  94.   
  95.         ConfigurableWebApplicationContext wac =  
  96.                 (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);  
  97.         wac.setParent(parent);  
  98.         wac.setServletContext(servletContext);  
  99.         <span style="color: rgb(0, 0, 0);" >wac.setConfigLocation(servletContext.getInitParameter(CONFIG_LOCATION_PARAM));</span>  
  100.   
  101.   
  102.   
  103.   
  104.   
  105.   
  106. customizeContext(servletContext, wac);  
  107.         wac.refresh();  
  108.   
  109.         return  wac;  
  110.     }  
  111.   
  112.         protected  Class determineContextClass(ServletContext servletContext)  throws  ApplicationContextException {  
  113.         String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);  
  114.         if  (contextClassName !=  null ) {  
  115.             try  {  
  116.                 return  ClassUtils.forName(contextClassName);  
  117.             }  
  118.             catch  (ClassNotFoundException ex) {  
  119.                 throw   new  ApplicationContextException(  
  120.                         "Failed to load custom context class ["  + contextClassName +  "]" , ex);  
  121.             }  
  122.         }  
  123.         else  {  
  124.             contextClassName = defaultStrategies.getProperty(WebApplicationContext.class .getName());  
  125.             try  {  
  126.                 return  ClassUtils.forName(contextClassName, ContextLoader . class .getClassLoader());  
  127.             }  
  128.             catch  (ClassNotFoundException ex) {  
  129.                 throw   new  ApplicationContextException(  
  130.                         "Failed to load default context class ["  + contextClassName +  "]" , ex);  
  131.             }  
  132.         }  
  133.     }  
  134.   
  135.         protected   void  customizeContext(  
  136.             ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) {  
  137.     }  
  138.   
  139.     protected  ApplicationContext loadParentContext(ServletContext servletContext)  
  140.             throws  BeansException {  
  141.   
  142.         ApplicationContext parentContext = null ;  
  143.         String locatorFactorySelector = servletContext.getInitParameter(LOCATOR_FACTORY_SELECTOR_PARAM);  
  144.         String parentContextKey = servletContext.getInitParameter(LOCATOR_FACTORY_KEY_PARAM);  
  145.   
  146.         if  (parentContextKey !=  null ) {  
  147.             // locatorFactorySelector may be null, indicating the default "classpath*:beanRefContext.xml"   
  148.             BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance(locatorFactorySelector);  
  149.             if  (logger.isDebugEnabled()) {  
  150.                 logger.debug("Getting parent context definition: using parent context key of '"  +  
  151.                         parentContextKey + "' with BeanFactoryLocator" );  
  152.             }  
  153.             this .parentContextRef = locator.useBeanFactory(parentContextKey);  
  154.             parentContext = (ApplicationContext) this .parentContextRef.getFactory();  
  155.         }  
  156.   
  157.         return  parentContext;  
  158.     }  
  159.   
  160.     public   void  closeWebApplicationContext(ServletContext servletContext) {  
  161.         servletContext.log("Closing Spring root WebApplicationContext" );  
  162.         try  {  
  163.             if  ( this .context  instanceof  ConfigurableWebApplicationContext) {  
  164.                 ((ConfigurableWebApplicationContext) this .context).close();  
  165.             }  
  166.         }  
  167.         finally  {  
  168.             currentContextPerThread.remove(Thread.currentThread().getContextClassLoader());  
  169.             servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);  
  170.             if  ( this .parentContextRef !=  null ) {  
  171.                 this .parentContextRef.release();  
  172.             }  
  173.         }  
  174.     }  
  175.   
  176.   
  177.     public   static  WebApplicationContext getCurrentWebApplicationContext() {  
  178.         return  (WebApplicationContext) currentContextPerThread.get(Thread.currentThread().getContextClassLoader());  
  179.     }  
  180.   
  181. }  
package org.springframework.web
.context;

public class ContextLoader
 {

	public static final String CONTEXT_CLASS_PARAM = "contextClass";

	public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";

       public static final String LOCATOR_FACTORY_SELECTOR_PARAM = "locatorFactorySelector";

	public static final String LOCATOR_FACTORY_KEY_PARAM = "parentContextKey";

	private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader
.properties";


	private static final Properties defaultStrategies;

	static {
				try {
			ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader
.class);
			defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
		}
		catch (IOException ex) {
			throw new IllegalStateException("Could not load 'ContextLoader
.properties': " + ex.getMessage());
		}
	}


	private static final Log logger = LogFactory.getLog(ContextLoader
.class);

	private static final Map currentContextPerThread = CollectionFactory.createConcurrentMapIfPossible(1);

	private WebApplicationContext context;

	private BeanFactoryReference parentContextRef;

	public WebApplicationContext initWebApplicationContext(ServletContext servletContext)

          throws IllegalStateException, BeansException {

		if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
			throw new IllegalStateException(
					"Cannot initialize context because there is already a root application context present - " +
					"check
 whether
 you
 have
 multiple
 ContextLoader
* definitions
 in
 your
 web
.xml!");
		}

		servletContext.log("Initializing Spring root WebApplicationContext");
		if (logger.isInfoEnabled()) {
			logger.info("Root WebApplicationContext: initialization started");
		}
		long startTime = System.currentTimeMillis();

		try {
			// Determine parent for root web
 application context, if any.
			ApplicationContext parent = loadParentContext(servletContext);

			// Store context in
 local instance variable, to guarantee that
			// it is available on ServletContext shutdown.
			this.context = createWebApplicationContext(servletContext, parent);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
			currentContextPerThread.put(Thread.currentThread().getContextClassLoader(), this.context);

			if (logger.isDebugEnabled()) {
				logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
						WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
			}
			if (logger.isInfoEnabled()) {
				long elapsedTime = System.currentTimeMillis() - startTime;
				logger.info("Root WebApplicationContext: initialization completed in
 " + elapsedTime + " ms");
			}

			return this.context;
		}
		catch (RuntimeException ex) {
			logger.error("Context initialization failed", ex);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
			throw ex;
		}
		catch (Error err) {
			logger.error("Context initialization failed", err);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
			throw err;
		}
	}

	protected WebApplicationContext createWebApplicationContext(
			ServletContext servletContext, ApplicationContext parent) throws BeansException {

		Class contextClass = determineContextClass(servletContext);
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
					"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
		}

		ConfigurableWebApplicationContext wac =
				(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
		wac.setParent(parent);
		wac.setServletContext(servletContext);
		wac.setConfigLocation(servletContext.getInitParameter(CONFIG_LOCATION_PARAM));







customizeContext(servletContext, wac);
		wac.refresh();

		return wac;
	}

		protected Class determineContextClass(ServletContext servletContext)

  


  
分享到:
评论

相关推荐

    官方原版源码spring-framework-5.1.4.RELEASE.zip

    首先,源码分析从`spring-framework-5.1.4.RELEASE-dist.zip`开始,这是Spring框架的基础组件包,包含了所有核心模块的类库和配置文件。主要模块有Core Container(核心容器)、Data Access/Integration(数据访问与...

    官方原版源码spring-framework-4.3.25.RELEASE.zip

    - **spring-framework-4.3.25.RELEASE-schema.zip**:提供了Spring XML配置文件的XSD架构,有助于验证XML配置文件的语法正确性。 4. **关键模块解析** - **Core Container**:核心容器包括Beans和Context模块,是...

    spring-boot-2.0.0.M7 源码包

    4. **SpringApplication**:这是Spring Boot应用的入口点,`org.springframework.boot.SpringApplication`类负责加载和初始化Spring应用上下文,处理命令行参数,加载配置文件等。 5. **YAML/Properties配置**:...

    spring源码分析(1-10)

    1. **Spring 事务处理**:Spring 提供了声明式事务管理,允许开发者在配置文件中定义事务边界,无需在业务逻辑代码中显式控制事务开始、提交和回滚。它主要基于AOP代理来实现,通过TransactionInterceptor拦截器进行...

    官方原版源码spring-framework-5.1.9.RELEASE.zip

    "schema.zip"则是XML配置文件的模式定义,帮助开发者理解和验证自己的配置文件。 源码分析从以下几个关键模块入手: 1. **Core Container**:这是Spring框架的基础,包括BeanFactory和ApplicationContext接口,...

    spring-instrument-tomcat源码

    2. `META-INF`目录:包含Maven的配置信息,如`pom.xml`和`MANIFEST.MF`,这些文件描述了项目的依赖关系和元数据。 3. `src`目录:包含了源代码,可以导入Eclipse或其他IDE进行学习和分析。 在源码中,我们可以看到`...

    spring-framework-bom源码

    在Spring Framework中,Spring Framework BOM(Bill of Materials)是一个Maven配置文件,它定义了Spring生态系统的各个模块的版本协调。这意味着,当你在你的项目中引入Spring Framework BOM,你可以确保所有Spring...

    官方原版源码 spring-5.2.8.RELEASE.zip

    而`spring-5.2.8.RELEASE-schema.zip`则包含了Spring的XML配置文件的XSD规范,这对于理解Spring的配置方式至关重要。 Spring框架的核心模块包括: 1. **Core Container**(核心容器):这是Spring的基础,包括 ...

    Spring Boot源码(spring-boot-2.6.2.zip)

    3. `org.springframework.boot.context.config.*`: 配置处理模块,用于读取和解析配置文件。 4. `org.springframework.boot.context.embedded.*`: 内嵌Web服务器的接口和实现。 5. `org.springframework.boot....

    spring-framework-1.0-m1.zip源码

    1. ApplicationContext:在Spring 1.0中,ApplicationContext是主要的上下文接口,负责加载配置文件,管理Bean,并提供事件发布等功能。它是所有其他Spring服务的基础。 2. BeanFactory:作为ApplicationContext的...

    spring源码解读-地址.txt

    根据提供的文件信息,本次解读将围绕Spring框架的核心概念与源码分析进行展开。Spring框架作为Java企业级开发中不可或缺的一部分,其源码的学习对于深入理解框架机制、提高开发效率具有重要意义。下面,我们将从以下...

    官方原版源码 spring-framework-5.2.9.RELEASE.zip

    1. **ApplicationContext**:这是Spring的核心接口,负责初始化、加载配置文件,管理Bean的生命周期。源码中可以看到它是如何解析XML或Java配置,创建并管理Bean的。 2. **BeanFactory**:作为ApplicationContext的...

    spring-source-4.2.4源码

    SpEL允许在配置文件或代码中动态地访问和修改对象属性,这对于依赖注入和条件逻辑的实现至关重要。 `spring-webmvc-4.2.4.RELEASE-sources`是Spring MVC的实现,它是Spring框架用于构建Web应用的核心模块。通过源码...

    官方原版源码spring-framework-5.0.13.RELEASE.zip

    - **spring-framework-5.0.13.RELEASE-schema.zip**:包含了Spring XML配置文件的XML Schema定义,有助于理解配置文件的结构和约束。 四、源码阅读指南 1. **初始化流程**:从`org.springframework.context....

    spring-data-hadoop-1.0.0源码包

    例如,`HadoopConfigUtils`类负责解析和加载Hadoop的配置文件,`HadoopConfigurationBeanFactoryPostProcessor`则用于在Spring容器启动时处理Hadoop配置。 2. **数据访问接口**:Spring Data Hadoop定义了一系列的...

    spring-framework-3.2.x-for-eclipse.rar

    本文将针对《spring-framework-3.2.x-for-eclipse.rar》这个压缩包文件,详细介绍如何在Eclipse开发环境中搭建Spring 3.2.x源码分析环境,并探讨其中的关键知识点。 首先,我们来看标题中的"spring-framework-3.2.x...

    spring-cloud-config-server 源码电子书

    从提供的文件内容看,电子书《spring-cloud-config-server 源码电子书》可能涉及了Spring Cloud Config Server的关键组件和内部机制的源码分析。这部分内容专注于ConfigServerBootstrapApplicationListener类的实现...

    spring-boot自定义starter的源码示例

    本文将深入探讨如何通过源码分析来创建一个自定义的Spring Boot Starter,以`demo-spring-boot-starter`为例。 首先,我们了解Starter的基本结构。每个Starter通常包含以下组件: 1. **pom.xml**:这是Maven项目...

    spring-framework-4.3.12.RELEASE--编译好的源码.rar

    通过跟踪`refresh()`方法,可以了解如何加载和解析配置文件,以及如何初始化Bean。 - `AOP`相关的类,如`AbstractAdvisingBeanPostProcessor`和`ProxyCreator`,揭示了Spring如何通过代理模式实现AOP功能。 通过...

Global site tag (gtag.js) - Google Analytics