spring源码–配置加载及初始化

spring源码–配置加载及初始化

一、简介

这里基于spring源码,介绍spring从加载到创建bean的整个流程。spring源码的代码量大,千头万绪,本文从框架、整体流程、核心代码入手。

二、核心类

要理解spring,首先需要知道spring的核心类及其功能。本文介绍是spring加载和bean加载。涉及主要类的类型有:
ApplicationContext相关类、BeanFactory相关类、BeanDefinition相关类。

2.1 ApplicationContext相关类

spring上下文为ApplicationContext,相关核心类的类图如下:
ApplicationContext

分析上面类图,核心类是:

  • AbstractRefreshableApplicationContext:ApplicationContext容器抽象类,子类为各具体容器类,如XmlWebApplicationContext;
  • DefaultListableBeanFactory:Bean容器类,装载有所有bean实例;

2.2 BeanFactory相关类

bean容器是BeanFactory,相关核心类图如下:
BeanFactory

分析上面类图,核心类如下:

  • DefaultListableBeanFactory:Bean容器类,装载有所有bean实例;
  • BeanDefinitionRegistry:注册Bean到BeanFactory容器中;

2.3 BeanDefinition相关类

BeanDefinition是bean的定义,相关类包含BeanDefinition的定义、读取、注册,相关类的类图如下:
BeanDefinition

分析上面类图,如下:

  • Document:Bean的原始定义;
  • DocumentLoader:读取加载Document;
  • BeanDefinition:Bean转换后的定义;
  • BeanDefinitionReader:读取加载BeanDefinition;
  • BeanDefinitionHolder:设置Bean名称及别名;
  • BeanDefinitionRegistry:对Bean进行注册;

三、流程

这里以web中spring加载流程为例,介绍各自主要流程。

3.1 ApplicationContext整体加载流程

由servlet容器(tomcat)启动时加载web.xml文件,触发整个流程。

加载web.xml中的ContextLoaderListener监听器
调用ContextLoaderListener.contextInitialized初始化方法
调用ContextLoader.initWebApplicationContext方法
调用ContextLoader.createWebApplicationContext方法,创建WebApplicationContext对象,默认是XmlWebApplicationContext
调用ContextLoad.configureAndRefreshWebApplicationContext方法,配置ConfigurableWebApplicationContext对象,包含注入ServletContext和contextConfigLocation地址,及后续解析初始化
调用ContextLoader.customizeContext方法,配置ConfigurableWebApplicationContext,由实现ApplicationContextInitializer接口的初始化类配置
调用ContextLoader.determineContextInitializerClasses方法,获取contextInitializerClasses参数指定的实现了ApplicationContextInitializer的类实例
调用AbstractApplicationContext.refresh方法,加载配置
3.1.1 加载ContextLoaderListener监听器

web中,加载ContextLoaderListener监听器位于web.xml中,源码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<listener>
		<!-- Spring监听器 -->
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
3.1.2 ContextLoaderListener监听器执行

ContextLoaderListener是实现ServletContextListener的监听器,跟随servlet容器启动而执行,初始化时加启动ContextLoader类的initWebApplicationContext初始化方法,源码如下:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}
}
3.1.3 WebApplicationContext创建

WebApplicationContext创建位于ContextLoader.initWebApplicationContext中,先确定ApplicationContext类型,接着创建ApplicationContext实例,最后对ApplicationContext实例进行配置,源码如下:

public class ContextLoader {
	//由servlet容器启动,初始化ApplicationContext
  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!");
     }

     servletContext.log("Initializing Spring root WebApplicationContext");
     Log logger = LogFactory.getLog(ContextLoader.class);
     if (logger.isInfoEnabled()) {
        logger.info("Root WebApplicationContext: initialization started");
     }
     long startTime = System.currentTimeMillis();

     try {
        // Store context in local instance variable, to guarantee that
        // it is available on ServletContext shutdown.
        if (this.context == null) {
					//创建ApplicationContext对象
           this.context = createWebApplicationContext(servletContext);
        }
        if (this.context instanceof ConfigurableWebApplicationContext) {
           ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
           if (!cwac.isActive()) {
              // The context has not yet been refreshed -> provide services such as
              // setting the parent context, setting the application context id, etc
              if (cwac.getParent() == null) {
                 // The context instance was injected without an explicit parent ->
                 // determine parent for root web application context, if any.
                 ApplicationContext parent = loadParentContext(servletContext);
                 cwac.setParent(parent);
              }
							//配置ApplicationContext对象
              configureAndRefreshWebApplicationContext(cwac, servletContext);
           }
        }
        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.isInfoEnabled()) {
           long elapsedTime = System.currentTimeMillis() - startTime;
           logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
        }

        return this.context;
     }
     catch (RuntimeException | Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
     }
  }

  //配置ApplicationContext
	protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
		if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
			// The application context id is still set to its original default value
			// -> assign a more useful id based on available information
      //设置ApplicationContext标识id
			String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
			if (idParam != null) {
				wac.setId(idParam);
			}
			else {
				// Generate default id...
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(sc.getContextPath()));
			}
		}

    //设置ServletContext对象
		wac.setServletContext(sc);
		//加载ApplictionContext配置文件
		String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
		if (configLocationParam != null) {
			wac.setConfigLocation(configLocationParam);
		}

		// The wac environment's #initPropertySources will be called in any case when the context
		// is refreshed; do it eagerly here to ensure servlet property sources are in place for
		// use in any post-processing or initialization that occurs below prior to #refresh
		ConfigurableEnvironment env = wac.getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
		}

		customizeContext(sc, wac);
		//配置ApplictionContext
		wac.refresh();
	}
}

3.2 ApplicationContext配置加载流程

由ContextLoader.configureAndRefreshWebApplicationContext方法内的wac.refresh()触发,即是ConfigurableWebApplicationContext.refresh()方法。这里流程直接查看源码:

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			//context刷新准备,如记录启动时间,修改context各个状态(closed为false,active为true),调用属性初始化方法initPropertySources();
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
      //获取BeanFactory,获取刷新的BeanFactory,先调用refreshBeanFactory()方法(该方法真正创建beanFactory),接着getBeanFactory()方法
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
      //预处理BeanFactory,配置BeanFactory的context,如ClassLoader和post-processor,
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				//设置部分Bean后置处理器,方法为空实现,由子类来实现。
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				//调用在context中作为beans注册的BeanFactoryPostProcessor
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				//注册bean的后置处理器(BeanPostProcessor),在Bean创建的时调用
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				//初始化context消息源(MessageSource)
				initMessageSource();

				// Initialize event multicaster for this context.
				//初始事件广播(ApplicationEventMulticaster)
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				//初始化其它bean,这是模板方法,由子类实现
				onRefresh();

				// Check for listener beans and register them.
				//注册监听器(实现了ApplicationListener接口)
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				//初始化所有的剩余单例
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				//完成初始化,调用LifecycleProcessor.onRefresh()刷新方法,发出ContextRefreshedEvent事件
				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();
			}
		}
	}
3.2.1 prepareRefresh方法

prepareRefresh源码如下:

protected void prepareRefresh() {
   this.startupDate = System.currentTimeMillis();
   this.closed.set(false);
   this.active.set(true);

   if (logger.isDebugEnabled()) {
      if (logger.isTraceEnabled()) {
         logger.trace("Refreshing " + this);
      }
      else {
         logger.debug("Refreshing " + getDisplayName());
      }
   }

   // Initialize any placeholder property sources in the context environment
	 //初始化环境配置参数,空方法,由子类实现
   initPropertySources();

   // Validate that all properties marked as required are resolvable
   // see ConfigurablePropertyResolver#setRequiredProperties
	 //属性检测
   getEnvironment().validateRequiredProperties();

   // Allow for the collection of early ApplicationEvents,
   // to be published once the multicaster is available...
   this.earlyApplicationEvents = new LinkedHashSet<>();
}

分析下:

  • 打标记,如标记ApplicationContext初始化开始;
  • 初始化环境中的配置的参数,initPropertySources(),是个空方法,由子类实现;
  • 属性验证,检测需要的属性是否已经放入环境中,getEnvironment().validateRequiredProperties();
3.2.2 obtainFreshBeanFactory 方法

obtainFreshBeanFactory源码如下:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	 //创建BeanFactory
   refreshBeanFactory();
  
	 //返回BeanFactory
   return getBeanFactory();
}

分析:

  • 读取bean配置,创建BeanFactory容器,具体流程后续介绍;
  • 返回创建的BeanFactory;
3.2.3 prepareBeanFactory方法

prepareBeanFactory源码如下:

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   // Tell the internal bean factory to use the context's class loader etc.
	 //设置BeanFactory加载器
   beanFactory.setBeanClassLoader(getClassLoader());
	 //设置BeanFactory的表达式解析器
   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
   //添加BeanFactory的属性编辑
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

   // Configure the bean factory with context callbacks.
   //添加实现ApplicationContextAwareProcessor的Bean后置处理器,装配各种Ware接口
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	 //设置需要忽略的自动装配接口
   beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
   beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
   beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
   beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

   // BeanFactory interface not registered as resolvable type in a plain factory.
   // MessageSource registered (and found for autowiring) as a bean.
	 //设置可以自动装配的bean,通过@Autowired注解
   beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
   beanFactory.registerResolvableDependency(ResourceLoader.class, this);
   beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
   beanFactory.registerResolvableDependency(ApplicationContext.class, this);

   // Register early post-processor for detecting inner beans as ApplicationListeners.
	 //添加ApplicationListenerDetector的Bean后置处理器,可以对初始化后的bean进行增强处理
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

   // Detect a LoadTimeWeaver and prepare for weaving, if found.
   //增加对AspecatJ支持
   if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      // Set a temporary ClassLoader for type matching.
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }

   // Register default environment beans.
	 //添加默认的环境变量bean
   if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
   }
   if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
   }
   if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
   }
}

分析:

  • 设置类加载器、表达式解析器、属性编辑器;
  • 添加ApplicationContextAwareProcessor的Bean后置处理器,用装配实现各种Ware接口,有EnvironmentAware | EmbeddedValueResolverAware | ResourceLoaderAware | ApplicationEventPublisherAware | MessageSourceAware | ApplicationContextAware;
  • 设置需要忽略的自动装配的接口;
  • 设置可以自动装配的bean,通过@Autowired注解,有BeanFactory|ResourceLoader|ApplicationEventPublisher|ApplicationContext;
  • 添加ApplicationListenerDetector的Bean后置处理器,可以对初始化后的bean进行增强处理
  • 增加对AspecatJ支持
  • 添加默认的环境变量bean
3.2.4 postProcessBeanFactory方法

postProcessBeanFactory是个空方法,由子类实现,源码如下:

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

在子类AbstractRefreshableWebApplicationContext.postProcessBeanFactory方法实现如下:

@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	 //添加ServletContextAwareProcessor后置处理器
   beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
   beanFactory.ignoreDependencyInterface(ServletContextAware.class);
   beanFactory.ignoreDependencyInterface(ServletConfigAware.class);

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

分析:

  • 添加ServletContextAwareProcessor后置处理器,处理ServletContextAware和ServletConfigAware实现类的ServletContext和ServletConfig的参数注入。
  • 容器涉及servlet的初始化。
3.2.5 invokeBeanFactoryPostProcessors方法

invokeBeanFactoryPostProcessors方法是调用BeanFactoryPostProcessor后置处理器,但真正实现逻辑在方法PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());中实现。

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//调用BeanFactoryPostProcessor后置处理器的真正实现逻辑
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

   // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
   // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
   if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }
}

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())源码如下 :

public static void invokeBeanFactoryPostProcessors(
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

   // Invoke BeanDefinitionRegistryPostProcessors first, if any.
   Set<String> processedBeans = new HashSet<>();

   if (beanFactory instanceof BeanDefinitionRegistry) {
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
         if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
            BeanDefinitionRegistryPostProcessor registryProcessor =
                  (BeanDefinitionRegistryPostProcessor) postProcessor;
            registryProcessor.postProcessBeanDefinitionRegistry(registry);
            registryProcessors.add(registryProcessor);
         }
         else {
            regularPostProcessors.add(postProcessor);
         }
      }

      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let the bean factory post-processors apply to them!
      // Separate between BeanDefinitionRegistryPostProcessors that implement
      // PriorityOrdered, Ordered, and the rest.
      List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor,也是BeanFactoryPostProcessor
      String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
     //按优先级排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();

      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
     //实现Ordered接口的BeanDefinitionRegistryPostProcessor,也是BeanFactoryPostProcessor
      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {

         if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
            processedBeans.add(ppName);
         }
      }
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();

      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			//其它的BeanDefinitionRegistryPostProcessor,也是BeanFactoryPostProcessor
      boolean reiterate = true;
      while (reiterate) {
         reiterate = false;
         postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
         for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName)) {
               currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
               processedBeans.add(ppName);
               reiterate = true;
            }
         }
         sortPostProcessors(currentRegistryProcessors, beanFactory);
         registryProcessors.addAll(currentRegistryProcessors);
         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
         currentRegistryProcessors.clear();
      }

      // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
   }

   else {
      // Invoke factory processors registered with the context instance.
      invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let the bean factory post-processors apply to them!
   String[] postProcessorNames =
         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

   // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
   // Ordered, and the rest.
   List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   List<String> orderedPostProcessorNames = new ArrayList<>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<>();
   for (String ppName : postProcessorNames) {
      if (processedBeans.contains(ppName)) {
         // skip - already processed in first phase above
      }
      else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
         priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
      }
      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
         orderedPostProcessorNames.add(ppName);
      }
      else {
         nonOrderedPostProcessorNames.add(ppName);
      }
   }

   // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
	//调用实现PriorityOrdered接口的BeanFactoryPostProcessors
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

   // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
//调用实现Ordered接口的BeanFactoryPostProcessors
   List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
   for (String postProcessorName : orderedPostProcessorNames) {
      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
   }
   sortPostProcessors(orderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

   // Finally, invoke all other BeanFactoryPostProcessors.
  //调用其它的BeanFactoryPostProcessors
   List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
   for (String postProcessorName : nonOrderedPostProcessorNames) {
      nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
   }
   invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

   // Clear cached merged bean definitions since the post-processors might have
   // modified the original metadata, e.g. replacing placeholders in values...
   beanFactory.clearMetadataCache();
}

分析:
invokeBeanFactoryPostProcessors方法用于调用BeanFactoryPostProcessor,流程为:

  • 调用实现了PriorityOrdered接口的BeanFactoryPostProcessor;
  • 调用实现了Ordered接口的BeanFactoryPostProcessor;
  • 调用实现了其它的BeanFactoryPostProcessor;
3.2.6 registerBeanPostProcessors方法

registerBeanPostProcessors方法是继续注册BeanPostProcessor,源码如下:

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

真正实现位于PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this)中,源码如下:

public static void registerBeanPostProcessors(
      ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

   String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

   // Register BeanPostProcessorChecker that logs an info message when
   // a bean is created during BeanPostProcessor instantiation, i.e. when
   // a bean is not eligible for getting processed by all BeanPostProcessors.
   int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
   beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

   // Separate between BeanPostProcessors that implement PriorityOrdered,
   // Ordered, and the rest.
  //注册实现PriorityOrdered接口的BeanPostProcessor
   List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
   List<String> orderedPostProcessorNames = new ArrayList<>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<>();
   for (String ppName : postProcessorNames) {
      if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
         priorityOrderedPostProcessors.add(pp);
         if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
         }
      }
      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
         orderedPostProcessorNames.add(ppName);
      }
      else {
         nonOrderedPostProcessorNames.add(ppName);
      }
   }

   // First, register the BeanPostProcessors that implement PriorityOrdered.
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

   // Next, register the BeanPostProcessors that implement Ordered.
  //注册实现Ordered接口的BeanPostProcessor
   List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
   for (String ppName : orderedPostProcessorNames) {
      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
      orderedPostProcessors.add(pp);
      if (pp instanceof MergedBeanDefinitionPostProcessor) {
         internalPostProcessors.add(pp);
      }
   }
   sortPostProcessors(orderedPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, orderedPostProcessors);

   // Now, register all regular BeanPostProcessors.
//注册其它的BeanPostProcessor
   List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
   for (String ppName : nonOrderedPostProcessorNames) {
      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
      nonOrderedPostProcessors.add(pp);
      if (pp instanceof MergedBeanDefinitionPostProcessor) {
         internalPostProcessors.add(pp);
      }
   }
   registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

   // Finally, re-register all internal BeanPostProcessors.
   sortPostProcessors(internalPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, internalPostProcessors);

   // Re-register post-processor for detecting inner beans as ApplicationListeners,
   // moving it to the end of the processor chain (for picking up proxies etc).
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

分析:
和BeanFactoryPostProcessor类似,按优先级注册BeanFactoryProcessor,具体如下:

  • 注册实现了PriorityOrdered接口的BeanPostProcessor;
  • 注册实现了Ordered接口的BeanPostProcessor;
  • 注册其它的BeanPostProcessor;
3.2.7 initMessageSource方法

initMessageSource方法用于初始化消息源,常在国际化中使用,源码如下:

protected void initMessageSource() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		
   if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
			//若已经存在MessageSource,则直接提取记录
      this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
      // Make MessageSource aware of parent MessageSource.
      if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
         HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
         if (hms.getParentMessageSource() == null) {
            // Only set parent context as parent MessageSource if no parent MessageSource
            // registered already.
            hms.setParentMessageSource(getInternalParentMessageSource());
         }
      }
      if (logger.isTraceEnabled()) {
         logger.trace("Using MessageSource [" + this.messageSource + "]");
      }
   }
   else {
      // Use empty MessageSource to be able to accept getMessage calls.
     //若不存在MessageSource,则new一个并记录
      DelegatingMessageSource dms = new DelegatingMessageSource();
      dms.setParentMessageSource(getInternalParentMessageSource());
      this.messageSource = dms;
      beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
      if (logger.isTraceEnabled()) {
         logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
      }
   }
}

分析:
初始化消息源,若存在,则直接记录,若不存在,则new一个新的并记录。

3.2.8 initApplicationEventMulticaster方法

initApplicationEventMulticaster方法为初始化事件广播器(事件源),源码如下:

protected void initApplicationEventMulticaster() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//若已经存在ApplicationEventMulticaster,则直接提取记录
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			if (logger.isTraceEnabled()) {
				logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}
		else {
      //若不存在ApplicationEventMulticaster,则new一个SimpleApplicationEventMulticaster并记录
			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
			if (logger.isTraceEnabled()) {
				logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
						"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
			}
		}
	}

分析:
这里逻辑同initMessageSource方法类似,判断是否已经存在ApplicationEventMulticaster事件监听器,有则直接记录,没有则新建一个并记录。

3.2.9 onRefresh方法

onRefresh方法是空实现,由子类具体实现,源码如下:

protected void onRefresh() throws BeansException {
   // For subclasses: do nothing by default.
}

具体实现如AbstractRefreshableWebApplicationContext.onRefresh(),初始化主题

protected void onRefresh() {
   this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}
3.2.10 registerListeners方法

registerListeners方法注册事件监听器,源码如下:

protected void registerListeners() {
   // Register statically specified listeners first.
	//静态指定(硬编码)监听器
   for (ApplicationListener<?> listener : getApplicationListeners()) {
      getApplicationEventMulticaster().addApplicationListener(listener);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let post-processors apply to them!
	//配置文件中的监听器
   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
   for (String listenerBeanName : listenerBeanNames) {
      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
   }

   // Publish early application events now that we finally have a multicaster...
  //广播早期事件
   Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
   this.earlyApplicationEvents = null;
   if (earlyEventsToProcess != null) {
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
         getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
   }
}

分析:
registerListeners方法为注册监听器,按通常逻辑,先代码中的监听器,再用户配置的监听器,最后广播早期事件。

3.2.11 finishBeanFactoryInitialization方法

finishBeanFactoryInitialization方法完成BeanFactory初始化,源码如下:

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // Initialize conversion service for this context.
//初始化convert
   if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(
            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
   }

   // Register a default embedded value resolver if no bean post-processor
   // (such as a PropertyPlaceholderConfigurer bean) registered any before:
   // at this point, primarily for resolution in annotation attribute values.
   if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
   }

   // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
   }

   // Stop using the temporary ClassLoader for type matching.
   beanFactory.setTempClassLoader(null);

   // Allow for caching all bean definition metadata, not expecting further changes.
  //冻结Bean定义
   beanFactory.freezeConfiguration();

   // Instantiate all remaining (non-lazy-init) singletons.
//初始化其它(未被初始化)bean
   beanFactory.preInstantiateSingletons();
}

分析:

完成初始化,配置初始化convert,冻结已经存在的bean,初始化其它(未被初始化)的bean。

3.2.12 finishRefresh方法

finishRefresh方法完成初始化,清空缓存,初始化生命周期processor,发布ContextRefreshedEvent事件,源码如下:

protected void finishRefresh() {
   // Clear context-level resource caches (such as ASM metadata from scanning).
	//清空缓存
   clearResourceCaches();

   // Initialize lifecycle processor for this context.
	//初始化生命周期相关的processor
   initLifecycleProcessor();

   // Propagate refresh to lifecycle processor first.
	//传播refresh给生命周期相关的processor
   getLifecycleProcessor().onRefresh();

   // Publish the final event.
	//发布ContextRefreshedEvent事件
   publishEvent(new ContextRefreshedEvent(this));

   // Participate in LiveBeansView MBean, if active.
   LiveBeansView.registerApplicationContext(this);
}

3.3 BeanFactory加载流程

BeanFactory加载分为BeanFactory对象创建、xml格式bean定义解析、BeanDefinition的注册。

3.3.1 BeanFactory对象创建

BeanFactory对象创建位于AbstractRefreshableApplicationContext类的refreshBeanFactory方法中,源码如下:

public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
	@Override
	protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			//创建DefaultListableBeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			//加载BeanDefinition定义
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}
  
  protected DefaultListableBeanFactory createBeanFactory() {
		//真正新生成BeanFactory对象
		return new DefaultListableBeanFactory(getInternalParentBeanFactory());
	}
}

分析源码,先生成DefaultListableBeanFactory对象,接下来加载BeanDefinition定义。

3.3.2 BeanDefinition定义加载

BeanDefinition定义加载先由AbstractXmlApplicationContext类执行,提前生成读取bean定义的reader,接口加载config配置信息,源码如下:

public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
  protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
     // Create a new XmlBeanDefinitionReader for the given BeanFactory.
		 //生成读取BeanDefinition定义的reader
     XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

     // Configure the bean definition reader with this context's
     // resource loading environment.
     beanDefinitionReader.setEnvironment(this.getEnvironment());
     beanDefinitionReader.setResourceLoader(this);
     beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

     // Allow a subclass to provide custom initialization of the reader,
     // then proceed with actually loading the bean definitions.
     initBeanDefinitionReader(beanDefinitionReader);
		 //加载BeanDefinition定义
     loadBeanDefinitions(beanDefinitionReader);
  }
  
  protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		//获取config配置文件(包含Bean定义)
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			//使用提前生成reader对资源进行加载
			reader.loadBeanDefinitions(configLocations);
		}
	}
}

接着XmlBeanDefinitionReader对配置文件进行解析,生成生成Document对象,源码如下:

public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {

  protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			//解析配置文件,生成Document对象
			Document doc = doLoadDocument(inputSource, resource);
			//bean对象注册
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
		catch (BeanDefinitionStoreException ex) {
			throw ex;
		}
    
    ...省略
  }

	//bean对象注册
	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//创建BeanDefinitionDocumentReader对象
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		int countBefore = getRegistry().getBeanDefinitionCount();
		//BeanDefinition注册
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}
}
3.3.3 BeanDefinition注册

BeanDefinition注册位于DefaultBeanDefinitionDocumentReader类中,

public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {
	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
    //BeanDefinition注册
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}
	//BeanDefinition注册
	protected void doRegisterBeanDefinitions(Element root) {
		// Any nested <beans> elements will cause recursion in this method. In
		// order to propagate and preserve <beans> default-* attributes correctly,
		// keep track of the current (parent) delegate, which may be null. Create
		// the new (child) delegate with a reference to the parent for fallback purposes,
		// then ultimately reset this.delegate back to its original (parent) reference.
		// this behavior emulates a stack of delegates without actually necessitating one.
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);

		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				// We cannot use Profiles.of(...) since profile expressions are not supported
				// in XML config. See SPR-12458 for details.
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}

		preProcessXml(root);
		//BeanDefinition解析
		parseBeanDefinitions(root, this.delegate);
		postProcessXml(root);

		this.delegate = parent;
	}
}
3.3.4 BeanDefinition解析

BeanDefinition解析位于AbstractBeanDefinitionParser类中,解析Element,生成BeanDefinition对象,源码如下:

public abstract class AbstractBeanDefinitionParser implements BeanDefinitionParser {
	@Override
	@Nullable
	public final BeanDefinition parse(Element element, ParserContext parserContext) {
		//生成eanDefinition对象
		AbstractBeanDefinition definition = parseInternal(element, parserContext);
		if (definition != null && !parserContext.isNested()) {
			try {
				String id = resolveId(element, definition, parserContext);
				if (!StringUtils.hasText(id)) {
					parserContext.getReaderContext().error(
							"Id is required for element '" + parserContext.getDelegate().getLocalName(element)
									+ "' when used as a top-level tag", element);
				}
				String[] aliases = null;
				if (shouldParseNameAsAliases()) {
					String name = element.getAttribute(NAME_ATTRIBUTE);
					if (StringUtils.hasLength(name)) {
						aliases = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
					}
				}
				//生成BeanDefinitionHolder对象
				BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id, aliases);
				//最终Bean注册
				registerBeanDefinition(holder, parserContext.getRegistry());
				if (shouldFireEvents()) {
					BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder);
					postProcessComponentDefinition(componentDefinition);
					parserContext.registerComponent(componentDefinition);
				}
			}
			catch (BeanDefinitionStoreException ex) {
				String msg = ex.getMessage();
				parserContext.getReaderContext().error((msg != null ? msg : ex.toString()), element);
				return null;
			}
		}
		return definition;
	}
}

四、回顾

spring的加载和初始化过程冗长复杂,类和接口继承实现链条长,方法重载和重写多。不过初步理解下来,大体流程还是清晰的,如下:

容器启动
加载spring配置文件
创建ApplicationContext对象
创建BeanFactory对象
加载Bean
调用Bean后置处理器
发布了274 篇原创文章 · 获赞 95 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/chinabestchina/article/details/105500455