Webx启动流程

1 WebxContextLoaderListener

      Webx Framework 通过配置在web.xml中的WebxContextLoaderListener来初始化Spring
    
     
    
        com.alibaba.citrus.webx.context.WebxContextLoaderListener
    
  WebxContextLoaderListener 是ContextLoaderListener的派生类。它定制了自己的ContextLoader——WebxComponentsLoader}       
       
        
  
 public class WebxContextLoaderListener extends ContextLoaderListener {    
     @Override
    protected final ContextLoader createContextLoader() {
        return new WebxComponentsLoader() {

            @Override
            protected Class getDefaultContextClass() {
                Class defaultContextClass = WebxContextLoaderListener.this
                        .getDefaultContextClass();

                if (defaultContextClass == null) {
                    defaultContextClass = super.getDefaultContextClass();
                }

                return defaultContextClass;
            }
        };
    }

    protected Class getDefaultContextClass() {
        return null;
    }
}

WebxComponentsLoader

其与基类ContextLoader相比,定义了一些自己的字段:
 
   
     
public class WebxComponentsLoader extends ContextLoader {
    private final static Logger log = LoggerFactory.getLogger(WebxComponentsLoader.class);
    private String webxConfigurationName;
    private ServletContext servletContext;
    private WebApplicationContext componentsContext;
    private WebxComponentsImpl components;
    ...
}

 
  
之后,使用代理模式由WebxComponentsLoader调用initWebApplicationContext继续初始化过程。实际上,initWebApplicationContext是其基类ContextLoader的方法,而WebxComponentsLoader重写了此方法
  
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws IllegalStateException,
            BeansException {
        this.servletContext = servletContext;
        init();

        return super.initWebApplicationContext(servletContext);
    }

        这里,WebxComponentsLoader获取了servletContext, 通过init方法设置context中 WebxConfiguration的名称。然后继续调用基类的同名方法,root application开始初始化。
    
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
		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!");
		}

		Log logger = LogFactory.getLog(ContextLoader.class);
		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);

			ClassLoader ccl = Thread.currentThread().getContextClassLoader();
			if (ccl == ContextLoader.class.getClassLoader()) {
				currentContext = this.context;
			}
			else if (ccl != null) {
				currentContextPerThread.put(ccl, 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;
		}
	}
此方法中最重要的部分是对应用上下文WebApplicationContext的创建

WebApplicationContext

       在createWebApplicationContext方法中,定义了ConfigurableWebApplicationContext 对象wac.
ConfigurableWebApplicationContext wac =
				(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
       查看BeanUtils.instantiateClass(contextClass);代码可以发现,此方法就是检查contextClass对象是否为空或者是接口,如果都不是的话则调用contextClass的构造方法构造ContextClass对象,并且转型为ConfigurableWebApplicationContext 。
       

       wac在返回给ContextLoader前,主要完成以下几个过程:
      
                wac.setParent(parent);
		wac.setServletContext(sc);
		wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM));
		customizeContext(sc, wac);
		wac.refresh();

      wac.setServletContext(sc);将WebxComponentsLoader的servletContext 传递给 wac。
      customizeContext(sc, wac);定制context, 设置其loader为WebxComponentsLoader。
    
      经过前几个步骤的准备工作后,由refresh方法初始化所有bean。
  
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) {
				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

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

				// Propagate exception to caller.
				throw ex;
			}
		}
	}
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 这一步骤根据webx.xml的配置获取相关的配置文件。如:
   

    

    
    

    
    

    
    

finishRefresh函数通过调用WebxComponentsLoader的finishRefresh方法,初始化所有子components:
protected void finishRefresh() {
        super.finishRefresh();
        getLoader().finishRefresh();
    }

webxComponents中的finishRefresh方法:
 public void finishRefresh() {
        ...

        for (WebxComponent component : components) {
            logInBothServletAndLoggingSystem("Initializing Spring sub WebApplicationContext: " + component.getName());

            WebxComponentContext wcc = (WebxComponentContext) component.getApplicationContext();
            WebxController controller = component.getWebxController();

            wcc.refresh();
            controller.onFinishedProcessContext();
        }

        logInBothServletAndLoggingSystem("WebxComponents: initialization completed");
    }

这里的wcc 是WebxComponentContext, 不同于之前的wac对象(WebxComponent sContext),不会在结束时调用子component进行初始化。


初始化流程草图如下:

Webx启动流程_第1张图片


你可能感兴趣的:(java,web,Webx3.0)