Spring 啓動記錄(10)

Spring 處理BeanDefinitionjava

一、此時回到啦麼久遠的一個停駐點web

public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      //說了那麼多這個方法剛走完
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      //-----------------繼續剩下的工做啦,看來還有好多要分析。。繼續戰鬥吧
      // Prepare the bean factory for use in this context.
      //
      prepareBeanFactory(beanFactory);

      try {
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory);

         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

 

postProcessBeanFactory:添加加一些處理類,須要忽略注入的類spring

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
   beanFactory.ignoreDependencyInterface(ServletContextAware.class);
   beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
   
  //註冊Scope對象
   WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, ServletContext sc) {
   beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST(request), new RequestScope());
   beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION(session), new SessionScope(false));
   beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION(globalSessoin), new SessionScope(true));
   if (sc != null) {
      ServletContextScope appScope = new ServletContextScope(sc);
      beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION(application), appScope);
      // Register as ServletContext attribute, for ContextCleanupListener to detect it.
      sc.setAttribute(ServletContextScope.class.getName(), appScope);
   }

   beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
   
   beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
   beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
   beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
   if (jsfPresent) {
      FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
   }
}

ServletContextAwareProcessor 很明顯是給ServletContextAware設置express

setServletContext,setServletConfig兩個對象的apache

/*
 * Copyright 2002-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.context.support;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.context.ServletConfigAware;
import org.springframework.web.context.ServletContextAware;

/**
 * {@link org.springframework.beans.factory.config.BeanPostProcessor}
 * implementation that passes the ServletContext to beans that implement
 * the {@link ServletContextAware} interface.
 *
 * <p>Web application contexts will automatically register this with their
 * underlying bean factory. Applications do not use this directly.
 *
 * @author Juergen Hoeller
 * @author Phillip Webb
 * @since 12.03.2004
 * @see org.springframework.web.context.ServletContextAware
 * @see org.springframework.web.context.support.XmlWebApplicationContext#postProcessBeanFactory
 */
public class ServletContextAwareProcessor implements BeanPostProcessor {

   private ServletContext servletContext;

   private ServletConfig servletConfig;


   /**
    * Create a new ServletContextAwareProcessor without an initial context or config.
    * When this constructor is used the {@link #getServletContext()} and/or
    * {@link #getServletConfig()} methods should be overridden.
    */
   protected ServletContextAwareProcessor() {
   }

   /**
    * Create a new ServletContextAwareProcessor for the given context.
    */
   public ServletContextAwareProcessor(ServletContext servletContext) {
      this(servletContext, null);
   }

   /**
    * Create a new ServletContextAwareProcessor for the given config.
    */
   public ServletContextAwareProcessor(ServletConfig servletConfig) {
      this(null, servletConfig);
   }

   /**
    * Create a new ServletContextAwareProcessor for the given context and config.
    */
   public ServletContextAwareProcessor(ServletContext servletContext, ServletConfig servletConfig) {
      this.servletContext = servletContext;
      this.servletConfig = servletConfig;
   }


   /**
    * Returns the {@link ServletContext} to be injected or {@code null}. This method
    * can be overridden by subclasses when a context is obtained after the post-processor
    * has been registered.
    */
   protected ServletContext getServletContext() {
      if (this.servletContext == null && getServletConfig() != null) {
         return getServletConfig().getServletContext();
      }
      return this.servletContext;
   }

   /**
    * Returns the {@link ServletContext} to be injected or {@code null}. This method
    * can be overridden by subclasses when a context is obtained after the post-processor
    * has been registered.
    */
   protected ServletConfig getServletConfig() {
      return this.servletConfig;
   }

   @Override
   public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
      if (getServletContext() != null && bean instanceof ServletContextAware) {
         ((ServletContextAware) bean).setServletContext(getServletContext());
      }
      if (getServletConfig() != null && bean instanceof ServletConfigAware) {
         ((ServletConfigAware) bean).setServletConfig(getServletConfig());
      }
      return bean;
   }

   @Override
   public Object postProcessAfterInitialization(Object bean, String beanName) {
      return bean;
   }

}
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}

 

public static void registerEnvironmentBeans( 
    //註冊單利的ServletContext、ServletConfig、Servlet 的paramter、attribute等web的對象及參數
      ConfigurableListableBeanFactory bf, ServletContext servletContext, ServletConfig servletConfig) {

   if (servletContext != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) {
      bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, servletContext);
   }
  
   if (servletConfig != null && !bf.containsBean(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME)) {
      bf.registerSingleton(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME, servletConfig);
   }

   if (!bf.containsBean(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME)) {
      Map<String, String> parameterMap = new HashMap<String, String>();
      if (servletContext != null) {
         Enumeration<?> paramNameEnum = servletContext.getInitParameterNames();
         while (paramNameEnum.hasMoreElements()) {
            String paramName = (String) paramNameEnum.nextElement();
            parameterMap.put(paramName, servletContext.getInitParameter(paramName));
         }
      }
      if (servletConfig != null) {
         Enumeration<?> paramNameEnum = servletConfig.getInitParameterNames();
         while (paramNameEnum.hasMoreElements()) {
            String paramName = (String) paramNameEnum.nextElement();
            parameterMap.put(paramName, servletConfig.getInitParameter(paramName));
         }
      }
      bf.registerSingleton(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME,
            Collections.unmodifiableMap(parameterMap));
   }

   if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) {
      Map<String, Object> attributeMap = new HashMap<String, Object>();
      if (servletContext != null) {
         Enumeration<?> attrNameEnum = servletContext.getAttributeNames();
         while (attrNameEnum.hasMoreElements()) {
            String attrName = (String) attrNameEnum.nextElement();
            attributeMap.put(attrName, servletContext.getAttribute(attrName));
         }
      }
      bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME,
            Collections.unmodifiableMap(attributeMap));
   }
}
相關文章
相關標籤/搜索