---
title: "Spring Open Sourse Research(ContextLoaderListener Parts)"
author: "hotforcc"
date: "2007-08-25T09:21:08Z"
tags: []
categories: ["非技术"]
slug: "spring-open-sourse-research-contextloaderlistener-parts"
draft: false
lastmod: "2007-08-25T09:21:08Z"
id: 116597
url: "https://hotforcc.iteye.com/blog/116597"
---

Spring 源码分析(ContextLoaderListener Parts)  
ContextLoaderListener .java

java 代码

01. public class ContextLoaderListener implements ServletContextListener {
02. private ContextLoader contextLoader;
03. /\**
04. * Initialize the root web application context.
05. \*/
06. public void contextInitialized(ServletContextEvent event) {
07. this.contextLoader = createContextLoader();
08. this.contextLoader.initWebApplicationContext(event.getServletContext());
09. }
10. /\**
11. * Create the ContextLoader to use. Can be overridden in subclasses.
12. * @return the new ContextLoader
13. \*/
14. protected ContextLoader createContextLoader() {
15. return new ContextLoader();
16. }
17. /\**
18. * Return the ContextLoader used by this listener.
19. * @return the current ContextLoader
20. \*/
21. public ContextLoader getContextLoader() {
22. return this.contextLoader;
23. }
24. /\**
25. * Close the root web application context.
26. \*/
27. public void contextDestroyed(ServletContextEvent event) {
28. if (this.contextLoader != null) {
29. this.contextLoader.closeWebApplicationContext(event.getServletContext());
30. }
31. }
32. }

2ContectLoader.java  
//初始化工作,调用默认策略DEFAULT\_STRATEGIES\_PATH

java 代码

01. static {
02. // Load default strategy implementations from properties file.
03. // This is currently strictly internal and not meant to be customized
04. // by application developers.
05. try {
06. ClassPathResource resource = new ClassPathResource(DEFAULT\_STRATEGIES\_PATH, ContextLoader.class);
07. defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
08. }
09. catch (IOException ex) {
10. throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
11. }
12. }

调用默认策略DEFAULT\_STRATEGIES\_PATH  
Spring在web环境下会默认初始化XmlWebApplicationContext这个

defaultStrategies:

java 代码

1. # Default WebApplicationContext implementation class for ContextLoader.
2. # Used as fallback when no explicit context implementation has been specified as context-param.
3. # Not meant to be customized by application developers.
4. org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
5. this.contextLoader.initWebApplicationContext(event.getServletContext());

 初始化工作

java 代码

01. /\**
02. * Initialize Spring's web application context for the given servlet context,
03. * according to the "contextClass" and "contextConfigLocation" context-params.
04. * @param servletContext current servlet context
05. * @return the new WebApplicationContext
06. * @throws IllegalStateException if there is already a root application context present
07. * @throws BeansException if the context failed to initialize
08. * @see #CONTEXT\_CLASS\_PARAM
09. * @see #CONFIG\_LOCATION\_PARAM
10. \*/
11. public WebApplicationContext initWebApplicationContext(ServletContext servletContext)
12. throws IllegalStateException, BeansException {
13. if (servletContext.getAttribute(WebApplicationContext.ROOT\_WEB\_APPLICATION\_CONTEXT\_ATTRIBUTE) != null) {
14. throw new IllegalStateException(
15. "Cannot initialize context because there is already a root application context present - " +
16. "check whether you have multiple ContextLoader* definitions in your web.xml!");
17. }
18. servletContext.log("Initializing Spring root WebApplicationContext");
19. if (logger.isInfoEnabled()) {
20. logger.info("Root WebApplicationContext: initialization started");
21. }
22. long startTime = System.currentTimeMillis();
23. try {
24. // Determine parent for root web application context, if any.
25. ApplicationContext parent = loadParentContext(servletContext);
26. // Store context in local instance variable, to guarantee that
27. // it is available on ServletContext shutdown.
28. this.context = createWebApplicationContext(servletContext, parent);
29. servletContext.setAttribute(
30. WebApplicationContext.ROOT\_WEB\_APPLICATION\_CONTEXT\_ATTRIBUTE, this.context);
31. if (logger.isDebugEnabled()) {
32. logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
33. WebApplicationContext.ROOT\_WEB\_APPLICATION\_CONTEXT\_ATTRIBUTE + "]");
34. }
35. if (logger.isInfoEnabled()) {
36. long elapsedTime = System.currentTimeMillis() - startTime;
37. logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
38. }
39. return this.context;
40. }
41. catch (RuntimeException ex) {
42. logger.error("Context initialization failed", ex);
43. servletContext.setAttribute(WebApplicationContext.ROOT\_WEB\_APPLICATION\_CONTEXT\_ATTRIBUTE, ex);
44. throw ex;
45. }
46. catch (Error err) {
47. logger.error("Context initialization failed", err);
48. servletContext.setAttribute(WebApplicationContext.ROOT\_WEB\_APPLICATION\_CONTEXT\_ATTRIBUTE, err);
49. throw err;
50. }
51. }

 initWebApplicationContext()调用了createWebApplicationContext()

java 代码

01. /\**
02. * Instantiate the root WebApplicationContext for this loader, either the
03. * default context class or a custom context class if specified.
04. * This implementation expects custom contexts to implement
05. * ConfigurableWebApplicationContext. Can be overridden in subclasses.
06. * @param servletContext current servlet context
07. * @param parent the parent ApplicationContext to use, or null if none
08. * @return the root WebApplicationContext
09. * @throws BeansException if the context couldn't be initialized
10. * @see ConfigurableWebApplicationContext
11. \*/
12. protected WebApplicationContext createWebApplicationContext(
13. ServletContext servletContext, ApplicationContext parent) throws BeansException {
14. //取得代用的从Context Class ,WebApplicationContext default
15. Class contextClass = determineContextClass(servletContext);
16. //判断contextClass是否是ConfigurableWebApplicationContext的子类，如果不是，throws ApplicationContextException
17. if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
18. throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
19. "] is not of type \[" + ConfigurableWebApplicationContext.class.getName() + "]");
20. }
21. //初始化这个类
22. ConfigurableWebApplicationContext wac =
23. (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
24. wac.setParent(parent);
25. wac.setServletContext(servletContext);
26. String configLocation = servletContext.getInitParameter(CONFIG\_LOCATION\_PARAM);
27. if (configLocation != null) {
28. wac.setConfigLocations(StringUtils.tokenizeToStringArray(configLocation,
29. ConfigurableWebApplicationContext.CONFIG\_LOCATION\_DELIMITERS));
30. }
31. wac.refresh();
32. return wac;
33. }

    

java 代码

01. /\**
02. * Return the WebApplicationContext implementation class to use, either the
03. * default XmlWebApplicationContext or a custom context class if specified.
04. * @param servletContext current servlet context
05. * @return the WebApplicationContext implementation class to use
06. * @throws ApplicationContextException if the context class couldn't be loaded
07. * @see #CONTEXT\_CLASS\_PARAM
08. * @see org.springframework.web.context.support.XmlWebApplicationContext
09. \*/
10. protected Class determineContextClass(ServletContext servletContext) throws ApplicationContextException {
11. String contextClassName = servletContext.getInitParameter(CONTEXT\_CLASS\_PARAM);
12. if (contextClassName != null) {
13. try {
14. return ClassUtils.forName(contextClassName);
15. }
16. catch (ClassNotFoundException ex) {
17. throw new ApplicationContextException(
18. "Failed to load custom context class \[" + contextClassName + "]", ex);
19. }
20. }
21. else {
22. contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
23. try {
24. return ClassUtils.forName(contextClassName);
25. }
26. catch (ClassNotFoundException ex) {
27. throw new ApplicationContextException(
28. "Failed to load default context class \[" + contextClassName + "]", ex);
29. }
30. }
31. }

**Notice: public static final String CONTEXT\_CLASS\_PARAM = "contextClass";**

**BeanUtils.java**

    

java 代码

01. public static Object instantiateClass(Constructor ctor, Object\[] args) throws BeanInstantiationException {
02. Assert.notNull(ctor, "Constructor must not be null");
03. try {
04. if (!Modifier.isPublic(ctor.getModifiers()) ||
05. !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
06. ctor.setAccessible(true);
07. }
08. return ctor.newInstance(args);
09. }
10. catch (InstantiationException ex) {
11. throw new BeanInstantiationException(ctor.getDeclaringClass(),
12. "Is it an abstract class?", ex);
13. }
14. catch (IllegalAccessException ex) {
15. throw new BeanInstantiationException(ctor.getDeclaringClass(),
16. "Has the class definition changed? Is the constructor accessible?", ex);
17. }
18. catch (IllegalArgumentException ex) {
19. throw new BeanInstantiationException(ctor.getDeclaringClass(),
20. "Illegal arguments for constructor", ex);
21. }
22. catch (InvocationTargetException ex) {
23. throw new BeanInstantiationException(ctor.getDeclaringClass(),
24. "Constructor threw exception", ex.getTargetException());
25. }
26. }

**ConfigurableWebApplicationContext.java**

java 代码

01. public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext {
02. //context para value分隔符
03. String CONFIG\_LOCATION\_DELIMITERS = ",; \\t\\n";
04. void setServletContext(ServletContext servletContext);
05. void setServletConfig(ServletConfig servletConfig);
06. ServletConfig getServletConfig();
07. void setNamespace(String namespace);
08. String getNamespace();
09. void setConfigLocations(String\[] configLocations);
10. String\[] getConfigLocations();
11. }

**In a word, ContextLoaderListener invoke ContextLoader，and ContextLoader delegate and create ConfigurableWebApplicationContext**  
**ConfigurableWebApplicationContext is an object including web servlet context,servletconfig,and contextConfigLocation.**  
**Is is significant as follows**

**servletContext.setAttribute(WebApplicationContext.ROOT\_WEB\_APPLICATION\_CONTEXT\_ATTRIBUTE, this.context);**  
**context is an object of ConfigurableWebApplicationContext;**