`
hotforcc
  • 浏览: 60640 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring Open Sourse Research(ContextLoaderListener Parts)

阅读更多
Spring 源码分析(ContextLoaderListener Parts)
ContextLoaderListener .java
java 代码
  1.   
  2. public class ContextLoaderListener implements ServletContextListener {   
  3.   
  4.     private ContextLoader contextLoader;   
  5.   
  6.   
  7.     /**  
  8.      * Initialize the root web application context.  
  9.      */  
  10.     public void contextInitialized(ServletContextEvent event) {   
  11.         this.contextLoader = createContextLoader();   
  12.         this.contextLoader.initWebApplicationContext(event.getServletContext());   
  13.     }   
  14.   
  15.     /**  
  16.      * Create the ContextLoader to use. Can be overridden in subclasses.  
  17.      * @return the new ContextLoader  
  18.      */  
  19.     protected ContextLoader createContextLoader() {   
  20.         return new ContextLoader();   
  21.     }   
  22.   
  23.     /**  
  24.      * Return the ContextLoader used by this listener.  
  25.      * @return the current ContextLoader  
  26.      */  
  27.     public ContextLoader getContextLoader() {   
  28.         return this.contextLoader;   
  29.     }   
  30.   
  31.   
  32.     /**  
  33.      * Close the root web application context.  
  34.      */  
  35.     public void contextDestroyed(ServletContextEvent event) {   
  36.         if (this.contextLoader != null) {   
  37.             this.contextLoader.closeWebApplicationContext(event.getServletContext());   
  38.         }   
  39.     }   
  40.   
  41. }   
  42.   

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.   
  5. org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext   
  6.   
  7.   
  8. 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.   
  14.        if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {   
  15.            throw new IllegalStateException(   
  16.                    "Cannot initialize context because there is already a root application context present - " +   
  17.                    "check whether you have multiple ContextLoader* definitions in your web.xml!");   
  18.        }   
  19.   
  20.        servletContext.log("Initializing Spring root WebApplicationContext");   
  21.        if (logger.isInfoEnabled()) {   
  22.            logger.info("Root WebApplicationContext: initialization started");   
  23.        }   
  24.        long startTime = System.currentTimeMillis();   
  25.   
  26.        try {   
  27.            // Determine parent for root web application context, if any.   
  28.            ApplicationContext parent = loadParentContext(servletContext);   
  29.   
  30.            // Store context in local instance variable, to guarantee that   
  31.            // it is available on ServletContext shutdown.   
  32.            this.context = createWebApplicationContext(servletContext, parent);   
  33.            servletContext.setAttribute(   
  34.                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);   
  35.   
  36.            if (logger.isDebugEnabled()) {   
  37.                logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +   
  38.                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");   
  39.            }   
  40.            if (logger.isInfoEnabled()) {   
  41.                long elapsedTime = System.currentTimeMillis() - startTime;   
  42.                logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");   
  43.            }   
  44.   
  45.            return this.context;   
  46.        }   
  47.        catch (RuntimeException ex) {   
  48.            logger.error("Context initialization failed", ex);   
  49.            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);   
  50.            throw ex;   
  51.        }   
  52.        catch (Error err) {   
  53.            logger.error("Context initialization failed", err);   
  54.            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);   
  55.            throw err;   
  56.        }   
  57.    }   

 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.           
  17.        //判断contextClass是否是ConfigurableWebApplicationContext的子类,如果不是,throws ApplicationContextException   
  18.        if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {   
  19.            throw new ApplicationContextException("Custom context class [" + contextClass.getName() +   
  20.                    "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");   
  21.        }   
  22.        //初始化这个类   
  23.        ConfigurableWebApplicationContext wac =   
  24.                (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);   
  25.        wac.setParent(parent);   
  26.        wac.setServletContext(servletContext);   
  27.        String configLocation = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);   
  28.        if (configLocation != null) {   
  29.            wac.setConfigLocations(StringUtils.tokenizeToStringArray(configLocation,   
  30.                    ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));   
  31.        }   
  32.   
  33.        wac.refresh();   
  34.        return wac;   
  35.    }   

    
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.    }   
  27.      
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;
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics