ITeye博客

Spring Open Sourse Research(ContextLoaderListener Parts)

hotforcc · 2007-08-25 09:21 · spring · 非技术 · Markdown

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

java 代码

  1. public class ContextLoaderListener implements ServletContextListener {
  2. private ContextLoader contextLoader;
  3. /**
  4. * Initialize the root web application context.
  5. */
  6. public void contextInitialized(ServletContextEvent event) {
  7. this.contextLoader = createContextLoader();
  8. this.contextLoader.initWebApplicationContext(event.getServletContext());
  9. }
  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 代码

  1. static {
  2. // Load default strategy implementations from properties file.
  3. // This is currently strictly internal and not meant to be customized
  4. // by application developers.
  5. try {
  6. ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
  7. defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
  8. }
  9. 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 代码

  1. /**
  2. * Initialize Spring's web application context for the given servlet context,
  3. * according to the "contextClass" and "contextConfigLocation" context-params.
  4. * @param servletContext current servlet context
  5. * @return the new WebApplicationContext
  6. * @throws IllegalStateException if there is already a root application context present
  7. * @throws BeansException if the context failed to initialize
  8. * @see #CONTEXT_CLASS_PARAM
  9. * @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 代码

  1. /**
  2. * Instantiate the root WebApplicationContext for this loader, either the
  3. * default context class or a custom context class if specified.
  4. * This implementation expects custom contexts to implement
  5. * ConfigurableWebApplicationContext. Can be overridden in subclasses.
  6. * @param servletContext current servlet context
  7. * @param parent the parent ApplicationContext to use, or null if none
  8. * @return the root WebApplicationContext
  9. * @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 代码

  1. /**
  2. * Return the WebApplicationContext implementation class to use, either the
  3. * default XmlWebApplicationContext or a custom context class if specified.
  4. * @param servletContext current servlet context
  5. * @return the WebApplicationContext implementation class to use
  6. * @throws ApplicationContextException if the context class couldn't be loaded
  7. * @see #CONTEXT_CLASS_PARAM
  8. * @see org.springframework.web.context.support.XmlWebApplicationContext
  9. */
  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 代码

  1. public static Object instantiateClass(Constructor ctor, Object[] args) throws BeanInstantiationException {
  2. Assert.notNull(ctor, "Constructor must not be null");
  3. try {
  4. if (!Modifier.isPublic(ctor.getModifiers()) ||
  5. !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
  6. ctor.setAccessible(true);
  7. }
  8. return ctor.newInstance(args);
  9. }
  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 代码

  1. public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext {
  2. //context para value分隔符
  3. String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
  4. void setServletContext(ServletContext servletContext);
  5. void setServletConfig(ServletConfig servletConfig);
  6. ServletConfig getServletConfig();
  7. void setNamespace(String namespace);
  8. String getNamespace();
  9. 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;

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。