`
gstarwd
  • 浏览: 1490016 次
  • 性别: 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高级之注解驱动开发视频教程

    n 源码分析-@EnableAspectJAutoproxy注解加载过程分析 n 源码分析-AnnotationAwareAspectJAutoProxyCreator n 技术详解-切入点表达式详解 l Spring JDBC n 基础应用-JdbcTemplate的使用 n 源码分析-自定义...

    java8集合源码分析-app-engine:应用引擎

    区分有三种环境dev、test、prod,不同环境会加载不同的配置文件 Gradle环境配置: gradle.properties里设置profile Spring环境变量: application.yaml或application.properties里配置spring.profiles.active 应用内...

    java8集合源码分析-app-engine-maven:应用引擎Maven

    java8 集合源码分析 app-engine ...区分有三种环境dev、test、prod,不同环境会加载不同的配置文件 Gradle环境配置: gradle.properties里设置profile Spring环境变量: application.yaml或applicati

    spring2.5.6源码

    rar包内含有spring2.5.6源码,解压即可使用 源代码分析,是一件既痛苦又快乐的事情,看别人写的代码是通过的,但当你能够看明白的时候,相信快乐也会随之而来,为了减少痛苦,更快的带来快乐,在这里希望通过这篇...

    单点登录源码

    Spring+SpringMVC+Mybatis框架集成公共模块,包括公共配置、MybatisGenerator扩展插件、通用BaseService、工具类等。 &gt; zheng-admin 基于bootstrap实现的响应式Material Design风格的通用后台管理系统,`zheng`...

    springboot、logback源码解读

    springboot、logback源码解读,对logback从初始化到,配置文件加载到日志打印,所有步骤的源码分析

    一个带有注释的Redisson源码分析介绍

    然后,RedissonAutoConfiguration 根据配置文件中的参数以及默认参数来创建 Redisson 的客户端对象,并将其注入到 Spring 容器中。这样,在应用中使用 Redisson 时,就可以直接注入 Redisson 对象,而不需要手动在...

    JAVA上百实例源码以及开源项目

     Java zip压缩包查看程序,应用弹出文件选择框,选择ZIP格式的压缩文件,可以像Winrar软件一样查看压缩文件内部的文件及文件夹,源码截图如上所示。 Java 数字签名、数字证书生成源码 2个目标文件 摘要:JAVA源码,...

    JAVA上百实例源码以及开源项目源代码

     Java zip压缩包查看程序,应用弹出文件选择框,选择ZIP格式的压缩文件,可以像Winrar软件一样查看压缩文件内部的文件及文件夹,源码截图如上所示。 Java 数字签名、数字证书生成源码 2个目标文件 摘要:JAVA源码,...

    leetcode下载-blogNote:个人博客学习笔记

    配置文件顺序加载还未分析 SpringBoot学习笔记(五)-SpringBoot如何启动内嵌的tomcat 链表 题目编号 代码 题解 备注 难度 medium 使用双指针法 medium 迭代法递归法 easy Se存储判断使用双指针法 easy 双指针法 ...

    基于SpringBoot+Vue搭建的多功能体育场地智能管理系统源码+数据库+项目说明.zip

    * 将`gms.sql`中的sql文件运行,并修改对应的配置文件durid * 具体设置在`application.properties`里修改,如果出现乱码请修改编码 ### 4.修改application.properties * 在`application.properties`配置文件中...

    基于flink的电商实时数据分析、推荐、风控项目java源码+项目使用说明.zip

    再由Kafka流入Flink和ClickHouse,Flink做用户行为的实时计算,ClickHouse做离线计算,支持动态数据分区与规则配置(Flink广播流),支持类与Jar文件的动态编译与动态加载,利用ProcessFunction复杂的自定义逻辑来...

    asp.net知识库

    革新:.NET 2.0的自定义配置文件体系初探 关于如何在ASP.NET 2.0中定制Expression Builders 怎么在ASP.NET 2.0中使用Membership asp.net 2.0-实现数据访问(1) ASP.NET 2.0 新特性 .NET 2.0里使用强类型数据创建...

    java开源包8

    [ini4j] 是一个简单的Java类库,用来读写Windows的ini配置文件。同时还包含一个 Java Perferences API 的实现。 拒绝服务测试工具 Port Groper PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的...

    java开源包1

    [ini4j] 是一个简单的Java类库,用来读写Windows的ini配置文件。同时还包含一个 Java Perferences API 的实现。 拒绝服务测试工具 Port Groper PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的...

    java开源包10

    [ini4j] 是一个简单的Java类库,用来读写Windows的ini配置文件。同时还包含一个 Java Perferences API 的实现。 拒绝服务测试工具 Port Groper PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的...

    java开源包11

    [ini4j] 是一个简单的Java类库,用来读写Windows的ini配置文件。同时还包含一个 Java Perferences API 的实现。 拒绝服务测试工具 Port Groper PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的...

    java开源包2

    [ini4j] 是一个简单的Java类库,用来读写Windows的ini配置文件。同时还包含一个 Java Perferences API 的实现。 拒绝服务测试工具 Port Groper PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的...

    java开源包3

    [ini4j] 是一个简单的Java类库,用来读写Windows的ini配置文件。同时还包含一个 Java Perferences API 的实现。 拒绝服务测试工具 Port Groper PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的...

Global site tag (gtag.js) - Google Analytics