点点滴滴啊

导航

 

前言

​ 为了记录 spring 的学习日志,以笔记的形式将学习过程记录下来,有问题或有遗漏请指出,谢谢!

现将spring boot启动流程进行梳理记录。

1. SpringApplication 准备

@SpringBootApplication
public class DomeApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(DomeApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }
}

使用 @SpringBootApplication 注解,标识启动类,它是一个复合注解,标识使用自动装配、通过扫描注解注入bean。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication{}

在启动类中,运行main方法,将调用SpringApplication.run

	public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
		return run(new Class<?>[] { primarySource }, args);
	}
	
	public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
		return new SpringApplication(primarySources).run(args);
	}
	
	public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
		return new SpringApplication(primarySources).run(args);
	}

通过源码看到,在SpringApplication.run中,使用primarySources构造 SpringApplication对象,然后调用run方法。准备工作在构造器中完成。

	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        // 用来获取 Resource 和 classLoader 以及加载资源。
		this.resourceLoader = resourceLoader;
		Assert.notNull(primarySources, "PrimarySources must not be null");
        // 存放主加载类。
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        // 推断 web 类型:servlet 或 reactive。
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
        // 获取 ApplicationContextInitializer 的实现类,进行上下文初始化。
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        // 获取应用事件监听器。
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        // 推导入口类。
		this.mainApplicationClass = deduceMainApplicationClass();
	}

2. SpringApplication 运行

run方法执行后,spring 开始正式运行。

public ConfigurableApplicationContext run(String... args) {
    // 计时器启动
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    // 配置服务器环境有无外设:如显示器、鼠标,如果需要这些数据需要cpu模拟。
    configureHeadlessProperty();
    // 获取 spring 运行监听器,从spring.factories文件中加载
    // 如: EventPublishingRunListener(SpringApplication application, String[] args)
    SpringApplicationRunListeners listeners = getRunListeners(args);
    // 1. 监听器发布应用准备启动 ApplicationStartingEvent 事件
    listeners.starting();
    try {
        // 将传入的参数进行封装。
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        //2. 准备应用程序环境,并触发事件
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        // 设置Introspector.getBeaninfo参数是否忽略与参数class关联的所有beanInfo
        configureIgnoreBeanInfo(environment);
        // 获取横幅对象
        Banner printedBanner = printBanner(environment);
        //3. 根据webApplicationType创建对应的spring context,并注册注释配置处理器
        context = createApplicationContext();
        // spring 启动错误回调
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                                                         new Class[] { ConfigurableApplicationContext.class }, context);
        //4. 准备 applicationContext
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
               
        //5. 刷新context
        refreshContext(context);
        
        //11. 上下文刷新后触发
        afterRefresh(context, applicationArguments);
        
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        // 发布started事件
        listeners.started(context);
        callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
        // 异常处理
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        // 触发running事件
        listeners.running(context);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}

2.1 触发SpringApplication开始启动事件

获取spring.factories中 key为SpringApplicationRunListener的对象实例。

	// SpringApplication类中
	private SpringApplicationRunListeners getRunListeners(String[] args) {
		Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
		return new SpringApplicationRunListeners(logger,
				getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
	}

# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener

创建EventPublishingRunListener对象时将SpringApplication中的监听器存入广播器中,进行事件广播

public EventPublishingRunListener(SpringApplication application, String[] args) {
   this.application = application;
   this.args = args;
   this.initialMulticaster = new SimpleApplicationEventMulticaster();
   for (ApplicationListener<?> listener : application.getListeners()) {
      this.initialMulticaster.addApplicationListener(listener);
   }
}
2.2 准备环境 prepareEnvironment

将系统配置和系统环境加载进 ConfigurableEnvironment 中,如果有spring cloud 项目 bootstrap上下文,则会优先加载spring cloud 配置和远程配置。

  
   /**
	* SpringApplication类中
    * 准备应用程序环境以及配置。
    * 将系统的相关属性和环境变量配置加载进应用配置对象中,并把main方法输入参数 args 解析后也加入到应用配置中。
    */
   private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
                                                      ApplicationArguments applicationArguments) {
       //1. 根据容器类型创建环境配置
       // 并将系统的相关属性(systemProperties)和环境变量配置(systemEnvironment)加载进应用配置的对象中
       ConfigurableEnvironment environment = getOrCreateEnvironment();
       
       //2. 设置配置属性转换器、添加应用默认配置、设置 profile
       configureEnvironment(environment, applicationArguments.getSourceArgs());
       
       //3. 将MutablePropertySources转换为ConfigurationPropertySourcesPropertySource,主要充当适配器
       ConfigurationPropertySources.attach(environment);
       
       //4. 发布 ApplicationEnvironmentPreparedEvent 事件
       // 其中 BootstrapApplicationListener 将引导spring cloud 上下文,加载 bootstrap 配置文件
       // ConfigFileApplicationListener 加载配置文件(application.yml)
       listeners.environmentPrepared(environment);
       
       //5. 将environment 中 spring.main 开头的配置绑定到 application 实例上
       bindToSpringApplication(environment);
       
       if (!this.isCustomEnvironment) {
           //6. 将 environment 转化为对应容器类型的 Environment 实例
           // StandardServletEnvironment、StandardReactiveWebEnvironment、StandardEnvironment
           environment = new EnvironmentConverter(getClassLoader())
               .convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
       }
       
       //7. 将MutablePropertySources 转换为 ConfigurationPropertySourcesPropertySource
       ConfigurationPropertySources.attach(environment);
       return environment;
   }
2.3 创建 createApplicationContext

创建时会根据应用类型 webApplicationType 创建对应的 ApplicationContext,并注册默认的 BeanDefinitionRegistryPostProcessor

   /**
    * SpringApplication类中
    * 创建对应的 ApplicationContext
    */	
	protected ConfigurableApplicationContext createApplicationContext() {
		Class<?> contextClass = this.applicationContextClass;
		if (contextClass == null) {
			try {
				switch (this.webApplicationType) {
				case SERVLET:
                        // AnnotationConfigServletWebServerApplicationContext
					contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
					break;
				case REACTIVE:
                        // AnnotationConfigReactiveWebServerApplicationContext
					contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
					break;
				default:
                        // AnnotationConfigApplicationContext
					contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
				}
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
			}
		}
		return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
	}

   // -------------------------------------------------------
   /**
    * 这三个ApplicationContext的构造器中,都会创建 AnnotatedBeanDefinitionReader 和 ClassPathBeanDefinitionScanner
    */	
	public AnnotationConfigServletWebServerApplicationContext() {
        // 根据注解注册bean
		this.reader = new AnnotatedBeanDefinitionReader(this);
        // 根据class path 扫描bean
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}
	public AnnotationConfigReactiveWebServerApplicationContext() {
		this.reader = new AnnotatedBeanDefinitionReader(this);
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}
	public AnnotationConfigApplicationContext() {
		this.reader = new AnnotatedBeanDefinitionReader(this);
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}

   /**
    * AnnotatedBeanDefinitionReader 中会注册几个 BeanDefinitionRegistryPostProcessor
    */	
	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		Assert.notNull(environment, "Environment must not be null");
		this.registry = registry;
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
	}

   /**
    * AnnotationConfigUtils.registerAnnotationConfigProcessors 
    * 注册注解后置处理器,将在 refresh 方法中被调用到。
    */	
	public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {
        
		// 获取 beanFactory
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
            // 设置默认排序器
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
            // 设置自动注入处理器
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

        // 注册 ConfigurationClassPostProcessor,他支持 @Configuration、@ComponentScans、@ComponentScan、@ImportResource、@Import 等注解进行注册bean。
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
        
		// 注册 AutowiredAnnotationBeanPostProcessor,支持使用 @Autowired 注解、Setter、@Value 自动注入、xml配置。
		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		// 支持 jsr250Present 时注册 CommonAnnotationBeanPostProcessor
		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		// 支持jpa,注册 PersistenceAnnotationBeanPostProcessor
		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		
        // 注册 EventListenerMethodProcessor ,为事件监听器提供支持
		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}
		
        // 注册 DefaultEventListenerFactory,设置默认的监听器工厂
		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}
2.4 准备 prepareContext

配置 applicationContext,调用 ApplicationContextInitializer 实现类

   /**
    * SpringApplication 中
    * 对 applicationContext 进行初始化设置。
    */
   private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
                               SpringApplicationRunListeners listeners, 
                               ApplicationArguments applicationArguments, Banner printedBanner) {
       //1. 设置环境
       context.setEnvironment(environment);
       //2. 设置 beanNameGenerator和bean 属性数据类型转换服务
       postProcessApplicationContext(context);
       //3. 调用 ApplicationContextInitializer
       applyInitializers(context);
       //4. 发布 contextPrepared 事件
       listeners.contextPrepared(context);
       if (this.logStartupInfo) {
           logStartupInfo(context.getParent() == null);
           logStartupProfileInfo(context);
       }
       //5. 获取 beanFactory
       ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
       //6. 注册args参数为单例bean
       beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
       if (printedBanner != null) {
           // 7. 注册banner为单例
           beanFactory.registerSingleton("springBootBanner", printedBanner);
       }
       //8. 设置 beanFactory 中可以覆盖定义 bean
       if (beanFactory instanceof DefaultListableBeanFactory) {
           ((DefaultListableBeanFactory) beanFactory)
                   .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
       }
       //9. 启用懒加载所有bean:在spring启动时不会加载bean,会在使用时进行加载
       if (this.lazyInitialization) {
           context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
       }
       //10 加载 main 方法所在的主类
       Set<Object> sources = getAllSources();
       Assert.notEmpty(sources, "Sources must not be empty");
       //11 将主类加载进beanFactory中
       load(context, sources.toArray(new Object[0]));
       //12 触发contextLoade事件
       listeners.contextLoaded(context);
   }

   /**
    * SpringApplication 中
    * 2. 设置 applicationContext
    */	
	protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
        //2.1 注册 bean 名称生成器
		if (this.beanNameGenerator != null) {
			context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
					this.beanNameGenerator);
		}
        //2.2 为上下文设置 资源加载器resourceLoader 和 classLoader
		if (this.resourceLoader != null) {
			if (context instanceof GenericApplicationContext) {
				((GenericApplicationContext) context).setResourceLoader(this.resourceLoader);
			}
			if (context instanceof DefaultResourceLoader) {
				((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader());
			}
		}
        //2.3 注册类型转换服务:ConversionService
		if (this.addConversionService) {
			context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance());
		}
	}

   /**
    * SpringApplication 中
    * 3. 调用 ApplicationContextInitializer 初始化接口
    */	
	protected void applyInitializers(ConfigurableApplicationContext context) {
		for (ApplicationContextInitializer initializer : getInitializers()) {
            // 检查泛型的类型与context一致
			Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
					ApplicationContextInitializer.class);
			Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
			initializer.initialize(context);
		}
	}
2.5 加载或刷新 refreshContext

该方法主要是将应用程序中的bean注册到spring application context 中,也就是 BeanFactory 中,进行统一管理;并且在注册前后对bean 进行增强处理,如BeanDefinitionRegistryPostProcessor `BeanFactoryPostProcessor` ,增强 bean 的注册。

 
   /**
    * SpringApplication 中
    */	
	private void refreshContext(ConfigurableApplicationContext context) {
		if (this.registerShutdownHook) {
			try {
                // 注册容器关闭钩子
				context.registerShutdownHook();
			}
			catch (AccessControlException ex) {
				// Not allowed in some environments.
			}
		}
		refresh((ApplicationContext) context);
	}

    /**
     * SpringApplication 中
     * 加载或刷新springContext 
     */
    @Override
    public void refresh() throws BeansException, IllegalStateException {
        // 同步
        synchronized (this.startupShutdownMonitor) {
            //1 准备上下文刷新:将 applicationContext标记为 active状态
            prepareRefresh();

            //2 刷新 beanFactory
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            //3 准备beanFactory,并手动注册一些bean、添加 BeanPostProcessor
            prepareBeanFactory(beanFactory);

            try {
                //4 对 beanFactory 进行后置处理,交由子类实现
                postProcessBeanFactory(beanFactory);

                //5 调用已经注册的BeanFactoryPostProcessors:如从xml中以及用scan扫描java config、Component、configuration加载java bean Definition到beanFactory中
                invokeBeanFactoryPostProcessors(beanFactory);

                //6 注册 BeanPostProcessor,仅仅是注册,调用在getBean的时候
                registerBeanPostProcessors(beanFactory);

                //7 初始化国际化资源 i18n
                initMessageSource();

                //8 初始化事件广播器
                initApplicationEventMulticaster();

                //9 留给子类实现的刷新方法,在子类中,会创建对应的web容器:tomcat、jetty
                onRefresh();

                //10 注册事件监听器
                registerListeners();

                //11 初始化非懒加载的bean
                finishBeanFactoryInitialization(beanFactory);

                //12 最后一步,完成刷新过程,发布应用事件
                finishRefresh();
            }
            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                                "cancelling refresh attempt: " + ex);
                }
                //发生异常,则将已经初始化的bean注销掉
                destroyBeans();

                // Reset 'active' flag.
                // 取消刷新,将active 置为false
                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();
            }
        }
    }
	



2.5.1 beanFactory 刷新准备

将spring context 标记为激活状态(active),并且初始化和验证配置文件,保证配置能被正确解析和指定的配置属性必须存在。

    /**
     * AbstractApplicationContext 中
     * 1. 准备刷新 
     */	
	protected void prepareRefresh() {
		// Switch to active.
		this.startupDate = System.currentTimeMillis();
        //1.1 激活
		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.
        //1.2 在上下文环境中初始化配置的占位符,启动时为空实现
		initPropertySources();

		// Validate that all properties marked as required are resolvable:
		// see ConfigurablePropertyResolver#setRequiredProperties
        //1.3 对所有的必要属性进行验证,如果有必要的属性没有配置,则会抛出异常
		getEnvironment().validateRequiredProperties();

        //1.4 保存刷新之前的监听器
		// Store pre-refresh ApplicationListeners...
		if (this.earlyApplicationListeners == null) {
			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
		}
		else {
            // 将监听器的状态重置
			// Reset local application listeners to pre-refresh state.
			this.applicationListeners.clear();
			this.applicationListeners.addAll(this.earlyApplicationListeners);
		}

        //1.5 收集事件,一旦广播器准备好就可以发布事件
		// Allow for the collection of early ApplicationEvents,
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}



2.5.2 beanFactory 获取
    /**
     * AbstractApplicationContext 中
     */		
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        //2.1 可以在该方法中刷新 beanFactory,如替换新的 beanFactory、重新配置 beanFactory等。
		refreshBeanFactory();
        //2.2 获取更新后的beanFactory
		return getBeanFactory();
	}

2.5.3 beanFactory 配置
    /**
     * AbstractApplicationContext 中
     * 3. 设置 beanFactory 
     */	
	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
        //3.1 设置类加载器
		beanFactory.setBeanClassLoader(getClassLoader());
        //3.2 设置el表达式解析器
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        // 
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
        //3.3 添加 BeanPostProcessor ,完成与bean相关的XXXAware接口的注入工作
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        //3.4 忽略这些接口的实现类中的依赖自动注入(setter注入),接口的依赖由 ApplicationContextAwareProcessor 统一处理注入的接口。
		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

        //3.5 注册自动装配对象,这样BeanFactory/ApplicationContext虽然没有以bean的方式被定义在工厂中,也支持自动注入。
		// BeanFactory interface not registered as resolvable type in a plain factory.
		// MessageSource registered (and found for autowiring) as a bean.
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

        //3.6 在 bean 初始化后,检查该bean是否为 ApplicationListener,如是则将其加入到SpringContext中
		// Register early post-processor for detecting inner beans as ApplicationListeners.
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
        //3.7 https://www.cnblogs.com/wade-luffy/p/6078446.html
		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()));
		}

        //3.8 注册默认的环境单例对象
		// Register default environment beans.
		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());
		}
	}
2.5.4 beanFactory 后置处理
	
    /**
     * AbstractApplicationContext 中
     * 对 beanFactory 进行后置处理,交由子类实现
     */	
	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	}
2.5.5 beanFactory 后置处理器调用

​ 首先根据顺序策略调用 BeanDefinitionRegistryPostProcessor 实现类。

​ 之后根据顺序策略调用 BeanFactoryPostProcessor 实现类, 同时实现了BeanDefinitionRegistryPostProcessorBeanFactoryPostProcessor接口的实现类比只实现BeanFactoryPostProcessor接口的实现类先调用。

顺序策略:优先调用实现了 PriorityOrdered 接口的实现类、在调用实现了 Ordered 接口的实现类,之后调用未实现前面两个接口的实现类。

BeanDefinitionRegistryPostProcessor接口提供了可以注册、删除BeanDefinition 的支持, BeanFactoryPostProcessor接口提供了添加或修改BeanDefinition 的属性支持。这两个接口执行时,操作的是 BeanDefinition,这时 bean 还未被实例化的

createApplicationContext 方法中会加载 ConfigurationClassPostProcessorAutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor,这几个 beanFactory 后置处理器将会在这里执行,进行扫描需要由spring管理的 BeanDefinition

  
   /**
    * AbstractApplicationContext 中
    * 5. 调用beanFactory后置处理器
    */	
	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		//5.1 实际调用
		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 
     * 5.1 调用beanFactory后置处理器
     * 后置处理器的执行流程
     */	
	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

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

        // beanFactory 是BeanDefinitionRegistry类型
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            // 常规的BeanFactoryPostProcessor
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
            // BeanDefinitionRegistryPostProcessor类型的对象
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                // 为BeanDefinitionRegistryPostProcessor实现类设置BeanDefinitionRegistry
				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<>();

            // 获取 BeanDefinitionRegistryPostProcessor 类型的bean名称集合,
            // 首先执行实现了 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor 实现类。
			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
                // 将实现了PriorityOrdered的 BeanDefinitionRegistryPostProcessor 对象加入集合
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
            // 对实现了PriorityOrdered的 BeanDefinitionRegistryPostProcessor 进行排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
            // 加入到 registryProcessors 集合中,对 注册处理器进行汇总
			registryProcessors.addAll(currentRegistryProcessors);
           
            // 调用钩子:BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
            // bean定义已经被加载,但是没有实例化的,允许添加自定义的bean定义
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            // 执行实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor 。
			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 集合中,对 注册处理器进行汇总
			registryProcessors.addAll(currentRegistryProcessors);
            
            // 调用钩子:BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry
            // 实现 PriorityOrdered 接口比实现 Ordered 接口的实现类先执行
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            // 清空当前集合
			currentRegistryProcessors.clear();

            // 执行其他的 BeanDefinitionRegistryPostProcessors 。
			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			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();
			}
			// 执行 BeanFactoryPostProcessor 和 BeanDefinitionRegistryPostProcessor 的共同实现类的 postProcessBeanFactory()。
            // 所有的bean 定义已经被加载,可以添加或修改其中的属性值,在 BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry 后面执行。
            
            // 保证 spring 提供的 BeanFactoryPostProcessor 实现类先被执行
			// 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);
		}

        // 执行其他未执行 postProcessBeanFactory() 方法的 BeanFactoryPostProcessor实现类。
		// 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.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

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

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		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();
	}
2.5.6 beanFactory 注册BeanPostProcessors

注册BeanPostProcessor 实现,BeanPostProcessor支持对bean进行增强,在bean创建前后进行特殊操作。

/**
 * postProcessBeforeInitialization:在创建好bean之后执行,支持在bean创建后进行增强,比如修改bean的属性、使用代理进行代理。
 *
 * postProcessAfterInitialization:在执行了bean的 init 方法后执行(实现了`InitializingBean#afterPropertiesSet()`接口或xml配置中指定了init-method 属性的bean)。
 * postProcessAfterInitialization 方法与 postProcessBeforeInitialization 方法一样,只是执行时机不一样,一个是在执行init方法之前,一个是在init方法之后。
 */	
public interface BeanPostProcessor {

	/**
	 * InitializingBean#afterPropertiesSet() 之前执行
	 */
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * InitializingBean#afterPropertiesSet() 之后执行
	 */
	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
}

注册 BeanPostProcessors。

	/**
	 * 
     * AbstractApplicationContext 中
     */	
	protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
	}

	/**
	 * PostProcessorRegistrationDelegate.registerBeanPostProcessors 
     * 5.1 向BeanFactory 注册 BeanPostProcessors 
     */	
	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		
        // 获取BeanPostProcessor 实现类的bean名称
		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.
        // 记录bean处理器的总数,用于记录执行过的处理器与记录的处理器个数是否一致
		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<>();
        // 内部BeanPostProcessor,也就是实现了MergedBeanDefinitionPostProcessor接口的类
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
        // 实现类Order接口的类
		List<String> orderedPostProcessorNames = new ArrayList<>();
        // 未实现Order接口的类
		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);
                // 记录内部BeanPostProcessor
				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.
        // 排序并注册实现了PriorityOrdered接口的BeanPostProcessors,包括了内部BeanPostProcessors
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

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

        // 注册未实现Order接口的BeanPostProcessors
		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
            // 记录内部BeanPostProcessor
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

        // 排序并重新注册内部BeanPostProcessors
		// 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));
	}
2.5.7 初始化MessageSource

初始化 MessageSource,将 MessageSource委托给 DelegatingMessageSource,并注册进 beanFactory 中

	
	/**
     * AbstractApplicationContext 中
     */	
	protected void initMessageSource() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
			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.
			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 + "]");
			}
		}
	}
2.5.8 初始化事件广播器
	/**
	 * 注册事件广播器,默认使用 SimpleApplicationEventMulticaster
	 */
	protected void initApplicationEventMulticaster() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		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 {
			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() + "]");
			}
		}
	}
2.5.9 初始化其他特殊bean
	// AbstractApplicationContext
	protected void onRefresh() throws BeansException {
		// For subclasses: do nothing by default.
	}
	
	// ServletWebServerApplicationContext
	@Override
	protected void onRefresh() {
		super.onRefresh();
		try {
			createWebServer();
		}
		catch (Throwable ex) {
			throw new ApplicationContextException("Unable to start reactive web server", ex);
		}
	}

	// ServletWebServerApplicationContext,创建web服务
	private void createWebServer() {
		WebServerManager serverManager = this.serverManager;
		if (serverManager == null) {
			String webServerFactoryBeanName = getWebServerFactoryBeanName();
			ReactiveWebServerFactory webServerFactory = getWebServerFactory(webServerFactoryBeanName);
			boolean lazyInit = getBeanFactory().getBeanDefinition(webServerFactoryBeanName).isLazyInit();
			this.serverManager = new WebServerManager(this, webServerFactory, this::getHttpHandler, lazyInit);
			getBeanFactory().registerSingleton("webServerGracefulShutdown",
					new WebServerGracefulShutdownLifecycle(this.serverManager));
			getBeanFactory().registerSingleton("webServerStartStop",
					new WebServerStartStopLifecycle(this.serverManager));
		}
		initPropertySources();
	}
2.5.10 注册事件到事件广播器中

注册事件监听器,并发布早期事件

	/**
	 * AbstractApplicationContext
	 */
	protected void registerListeners() {
        // 注册在spring boot启动时创建的监听器实例到事件广播器中: 
        // SpringApplication#prepareContext() 和 SpringApplication#applyInitializers() 中执行
        // ApplicationContextInitializer#initialize 时,添加的监听器
		for (ApplicationListener<?> listener : getApplicationListeners()) {
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

		// 查找应用中ApplicationListener实现类,获取beanName,注册到广播器中
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) {
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

        // 广播在之前捕获到的事件(在容器初始化完bean前发布的事件将会暂存在earlyApplicationEvents中,进行延迟发布)
		// Publish early application events now that we finally have a multicaster...
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
        // 这之后的事件都直接发布,不在暂存到earlyApplicationEvents中进行延迟发布
		this.earlyApplicationEvents = null;
		if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}
2.5.11 实例化剩余非lazy load bean

除懒加载标记的bean外,都将在这一步进行实例化。

	/**
	 * Finish the initialization of this context's bean factory,
	 * initializing all remaining singleton beans.
	 */
	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// Initialize conversion service for this context.
        // 注册类型转换服务:ConversionService,在 SpringApplication#postProcessApplicationContext 中默认已经注册
        // 这里进行再次检查
		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.
        // 再次检查是否有字符串转换器:StringValueResolver,没有则将解析委托给 PropertySourcesPropertyResolver
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

        // 先创建LoadTimeWeaverAware 类型的实例 bean
		// 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);
		
        // 允许缓存 bean definition 
		// Allow for caching all bean definition metadata, not expecting further changes.
		beanFactory.freezeConfiguration();

        // 实例化不是懒加载的bean
		// Instantiate all remaining (non-lazy-init) singletons.
		beanFactory.preInstantiateSingletons();
	}

	/**
	 * 实例化单例对象
	 */ 
	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) {
			logger.trace("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
		
        // 创建非懒加载的实例对象
		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
            // 获取顶层bean定义
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            // 不是抽象、单例、非懒加载
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                // 判断是否是工程bean
				if (isFactoryBean(beanName)) {
                    // 如果是工程bean,则添加前缀进行查找
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						FactoryBean<?> factory = (FactoryBean<?>) bean;
                        // 是否立即创建bean
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged(
									(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
                        // 如果需要立即创建,则马上创建
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
                    // 非 beanFactory 的,则马上创建
					getBean(beanName);
				}
			}
		}
		
		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) {
            // 获取单例对象,如果这个对象是 SmartInitializingSingleton 接口的实现类,
            // 则调用 afterSingletonsInstantiated() 方法
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}
2.5.12 最后一步刷新完成
	/**
	 * AbstractApplicationContext
	 */
	protected void finishRefresh() {
        // 清除上下文中的资源缓存
		// Clear context-level resource caches (such as ASM metadata from scanning).
		clearResourceCaches();

        // 注册 LifecycleProcessor 接口实现类,默认使用 DefaultLifecycleProcessor
		// Initialize lifecycle processor for this context.
		initLifecycleProcessor();

        // 触发刚刚注册的 LifecycleProcessor 接口实现类的 onRefresh 事件
		// Propagate refresh to lifecycle processor first.
		getLifecycleProcessor().onRefresh();

        // 发布上下文刷新完成事件
		// Publish the final event.
		publishEvent(new ContextRefreshedEvent(this));

        // 想bean视图注册上下文对象。
		// Participate in LiveBeansView MBean, if active.
		LiveBeansView.registerApplicationContext(this);
	}

总结

spring boot 启动流程主要经过初始化和加载监听器、准备应用程序环境(配置信息)、创建容器上下文、刷新容器上下文,其中最关键的是刷新上下文 refresh。在刷新上下文中,加载 BeanFactoryPostProcessor,使用 BeanFactoryPostProcessor加载程序中需要注入的BeanDefinition,准备事件广播器,最后创建单例并且不是懒加载的bean。

spring提供的后置处理器执行顺序:

  1. BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(BeanDefinitionRegistry)

    动态注册、修改与删除 BeanDefinition

  2. BeanFactoryPostProcessor#postProcessBeanFactory(ConfigurableListableBeanFactory)

    添加或修改 BeanDefinition 的属性

  3. doCreateBean

    创建bean

  4. 对bean注入依赖

  5. BeanPostProcessor#postProcessBeforeInitialization()

    创建 bean 之后,在对bean 进行注入依赖对象后,调用这个 bean 后置处理器。

  6. InitializingBean#afterPropertiesSet

    spring提供的 bean 进行初始化接口

  7. BeanPostProcessor#postProcessAfterInitialization()

    bean初始化完成后执行。

    如果是 InitializingBean的实现类,则在afterPropertiesSet 方法执行后执行,否则在BeanPostProcessor#postProcessBeforeInitialization()之后执行。

posted on 2021-02-25 17:55  丶点滴  阅读(405)  评论(0编辑  收藏  举报