Spring 源码分析(ContextLoaderListener Parts)
ContextLoaderListener .java
2ContectLoader.java
//初始化工作,调用默认策略DEFAULT_STRATEGIES_PATH
调用默认策略DEFAULT_STRATEGIES_PATH
Spring在web环境下会默认初始化XmlWebApplicationContext这个
defaultStrategies:
初始化工作
initWebApplicationContext()调用了createWebApplicationContext()
Notice: public static final String CONTEXT_CLASS_PARAM = "contextClass";
ContextLoaderListener .java
java 代码
- 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());
- }
- }
- }
2ContectLoader.java
//初始化工作,调用默认策略DEFAULT_STRATEGIES_PATH
java 代码
- static {
- // Load default strategy implementations from properties file.
- // This is currently strictly internal and not meant to be customized
- // by application developers.
- 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());
- }
- }
Spring在web环境下会默认初始化XmlWebApplicationContext这个
defaultStrategies:
java 代码
- # Default WebApplicationContext implementation class for ContextLoader.
- # Used as fallback when no explicit context implementation has been specified as context-param.
- # Not meant to be customized by application developers.
- org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
- this.contextLoader.initWebApplicationContext(event.getServletContext());
初始化工作
java 代码
- /**
- * Initialize Spring's web application context for the given servlet context,
- * according to the "contextClass" and "contextConfigLocation" context-params.
- * @param servletContext current servlet context
- * @return the new WebApplicationContext
- * @throws IllegalStateException if there is already a root application context present
- * @throws BeansException if the context failed to initialize
- * @see #CONTEXT_CLASS_PARAM
- * @see #CONFIG_LOCATION_PARAM
- */
- 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);
- 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;
- }
- }
initWebApplicationContext()调用了createWebApplicationContext()
java 代码
- /**
- * Instantiate the root WebApplicationContext for this loader, either the
- * default context class or a custom context class if specified.
- * This implementation expects custom contexts to implement
- * ConfigurableWebApplicationContext. Can be overridden in subclasses.
- * @param servletContext current servlet context
- * @param parent the parent ApplicationContext to use, or null if none
- * @return the root WebApplicationContext
- * @throws BeansException if the context couldn't be initialized
- * @see ConfigurableWebApplicationContext
- */
- protected WebApplicationContext createWebApplicationContext(
- ServletContext servletContext, ApplicationContext parent) throws BeansException {
- //取得代用的从Context Class ,WebApplicationContext default
- Class contextClass = determineContextClass(servletContext);
- //判断contextClass是否是ConfigurableWebApplicationContext的子类,如果不是,throws ApplicationContextException
- 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);
- String configLocation = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
- if (configLocation != null) {
- wac.setConfigLocations(StringUtils.tokenizeToStringArray(configLocation,
- ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));
- }
- wac.refresh();
- return wac;
- }
java 代码
- /**
- * Return the WebApplicationContext implementation class to use, either the
- * default XmlWebApplicationContext or a custom context class if specified.
- * @param servletContext current servlet context
- * @return the WebApplicationContext implementation class to use
- * @throws ApplicationContextException if the context class couldn't be loaded
- * @see #CONTEXT_CLASS_PARAM
- * @see org.springframework.web.context.support.XmlWebApplicationContext
- */
- protected Class determineContextClass(ServletContext servletContext) throws ApplicationContextException {
- String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
- if (contextClassName != null) {
- try {
- return ClassUtils.forName(contextClassName);
- }
- catch (ClassNotFoundException ex) {
- throw new ApplicationContextException(
- "Failed to load custom context class [" + contextClassName + "]", ex);
- }
- }
- else {
- contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
- try {
- return ClassUtils.forName(contextClassName);
- }
- catch (ClassNotFoundException ex) {
- throw new ApplicationContextException(
- "Failed to load default context class [" + contextClassName + "]", ex);
- }
- }
- }
Notice: public static final String CONTEXT_CLASS_PARAM = "contextClass";
BeanUtils.java
java 代码
- public static Object instantiateClass(Constructor ctor, Object[] args) throws BeanInstantiationException {
- Assert.notNull(ctor, "Constructor must not be null");
- try {
- if (!Modifier.isPublic(ctor.getModifiers()) ||
- !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
- ctor.setAccessible(true);
- }
- return ctor.newInstance(args);
- }
- catch (InstantiationException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Is it an abstract class?", ex);
- }
- catch (IllegalAccessException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Has the class definition changed? Is the constructor accessible?", ex);
- }
- catch (IllegalArgumentException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Illegal arguments for constructor", ex);
- }
- catch (InvocationTargetException ex) {
- throw new BeanInstantiationException(ctor.getDeclaringClass(),
- "Constructor threw exception", ex.getTargetException());
- }
- }
ConfigurableWebApplicationContext.java
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;
java 代码
- public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext {
- //context para value分隔符
- String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
- void setServletContext(ServletContext servletContext);
- void setServletConfig(ServletConfig servletConfig);
- ServletConfig getServletConfig();
- void setNamespace(String namespace);
- String getNamespace();
- void setConfigLocations(String[] configLocations);
- String[] getConfigLocations();
- }
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;