SpringBoot 刷新上下文1--主流程

SpringBoot刷新上下文一共七篇,基于SpringBoot 2.2.7.RELEASE,Spring 5.2.6.RELEASE
SpringBoot 刷新上下文1–主流程
SpringBoot 刷新上下文2–执行BeanDefinitionRegistryPostProcessor
SpringBoot 刷新上下文3–解析引导类
SpringBoot 刷新上下文4–处理ComponentScan
SpringBoot 刷新上下文5–处理其他注解
SpringBoot 刷新上下文6–加载并注册BeanDefinition
SpringBoot 刷新上下文7–执行BeanFactoryPostProcessor

SpringBoot刷新上下文,在run方法里面调refreshContext 方法。

//org.springframework.boot.SpringApplication#refreshContext
private void refreshContext(ConfigurableApplicationContext context) {
	refresh(context);
	if (this.registerShutdownHook) {
		try {
			context.registerShutdownHook();
		}
		catch (AccessControlException ex) {
			// Not allowed in some environments.
		}
	}
}

调了本类的refresh

//org.springframework.boot.SpringApplication#refresh
protected void refresh(ApplicationContext applicationContext) {
    Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
    //执行上下文的刷新方法
    ((AbstractApplicationContext) applicationContext).refresh();
}

AbstractApplicationContext 的 refresh 方法。从这里就进入了Spring的上下文。

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
		...

        // Tell the subclass to refresh the internal bean factory.
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		...

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

            ...
    }
}

这里只看 AbstractApplicationContext#refresh 中的两个方法,obtainFreshBeanFactory 用来获得BeanFactory,invokeBeanFactoryPostProcessors 用来初始化Spring的IOC。

1、获得BeanFactory

//org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    refreshBeanFactory();
    return getBeanFactory();
}

SpringBoot会根据环境创建三种上下文:

AnnotationConfigServletWebServerApplicationContext

AnnotationConfigReactiveWebServerApplicationContext

AnnotationConfigApplicationContext。

这三种上下文都继承了 GenericApplicationContext ,GenericApplicationContext 继承了 AbstractApplicationContext 。

1.1、刷新BeanFactory

private final AtomicBoolean refreshed = new AtomicBoolean();
private final DefaultListableBeanFactory beanFactory;
//org.springframework.context.support.GenericApplicationContext#refreshBeanFactory
protected final void refreshBeanFactory() throws IllegalStateException {
    if (!this.refreshed.compareAndSet(false, true)) {
        throw new IllegalStateException(
            "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
    }
    this.beanFactory.setSerializationId(getId());
}

这个方法并没有做什么处理,不像 ClassPathXmlApplicationContext 那样直接调用 AbstractRefreshableApplicationContext的 refreshBeanFactory 去 初始化ioc容器。

这里调了BeanFactory,但是并没有创建BeanFactory的逻辑。

创建BeanFactory的逻辑在构造器。

public GenericApplicationContext() {
    this.beanFactory = new DefaultListableBeanFactory();
}

当创建上面三种上下文的时候,会执行父上下文 GenericApplicationContext 创建一个 DefaultListableBeanFactory 。

1.2、获得BeanFactory

//org.springframework.context.support.GenericApplicationContext#getBeanFactory
public final ConfigurableListableBeanFactory getBeanFactory() {
    return this.beanFactory;
}

2、初始化IOC

实际调用的是 AbstractApplicationContext#invokeBeanFactoryPostProcessors 方法,利用Spring的BeanFactory的后置处理器初始化IOC。

//org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    //调用Spring的BeanFactory后知处理器。
    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()));
    }
}

调用BeanFactory的后置处理器

//org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List)
public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

    // Invoke BeanDefinitionRegistryPostProcessors first, if any.
    // 保存被处理过的bean的名称。
    Set<String> processedBeans = new HashSet<>();
	//beanFactory 是 DefaultListableBeanFactory ,实现了 BeanDefinitionRegistry
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
		//调用 BeanFactoryPostProcessor 的 postProcessBeanDefinitionRegistry
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                BeanDefinitionRegistryPostProcessor registryProcessor =
                    (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else {
                regularPostProcessors.add(postProcessor);
            }
        }
        //走到这里,registryProcessor 和 regularPostProcessors 分别是
        //registryProcessors 0 = {SharedMetadataReaderFactoryContextInitializer$CachingMetadataReaderFactoryPostProcessor} 
		//1 = {ConfigurationWarningsApplicationContextInitializer$ConfigurationWarningsPostProcessor} 
        //regularPostProcessors 0 = {ConfigFileApplicationListener$PropertySourceOrderingPostProcessor} 
        //registryProcessor 中的两个后知处理器执行了 postProcessBeanDefinitionRegistry 方法

        // 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.
        // 这里将BeanDefinitionRegistryPostProcessor 按 PriorityOrdered, Ordered, 和其他 区分
        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

        // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
        // postProcessorNames = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
        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);
            }
        }
        //processedBeans = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
        //currentRegistryProcessors = ConfigurationClassPostProcessor
        //排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        // 现在 registryProcessors = {ArrayList@3018}  size = 3
		// 0 = {SharedMetadataReaderFactoryContextInitializer$CachingMetadataReaderFactoryPostProcessor@3019} 
		// 1 = {ConfigurationWarningsApplicationContextInitializer$ConfigurationWarningsPostProcessor@3042} 
		// 2 = {ConfigurationClassPostProcessor@3301} 
        //调用 BeanDefinitionRegistryPostProcessors
        // 这里currentRegistryProcessors = ConfigurationClassPostProcessor
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        // currentRegistryProcessors 清空
        currentRegistryProcessors.clear();

        // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
        // 下面这一段调用 实现了 order 的 BeanDefinitionRegistryPostProcessors
        // postProcessorNames = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
        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);
            }
        }
        // processedBeans =  0 = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        // 现在 registryProcessors = {ArrayList@3018}  size = 3
		// 0 = {SharedMetadataReaderFactoryContextInitializer$CachingMetadataReaderFactoryPostProcessor@3019} 
		// 1 = {ConfigurationWarningsApplicationContextInitializer$ConfigurationWarningsPostProcessor@3042} 
		// 2 = {ConfigurationClassPostProcessor@3301} 
        //currentRegistryProcessors 为空
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
        // 调用所有其他的 BeanDefinitionRegistryPostProcessors
        // 这个循环里面没有任何操作。。。
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            //org.springframework.context.annotation.internalConfigurationAnnotationProcessor
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                // 这里是false
                if (!processedBeans.contains(ppName)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            // currentRegistryProcessors 为空
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }

        // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
        // 调用所有 postProcessBeanFactory
        // registryProcessors = org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer.CachingMetadataReaderFactoryPostProcessor,org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer.ConfigurationWarningsPostProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        //regularPostProcessors = org.springframework.boot.context.config.ConfigFileApplicationListener.PropertySourceOrderingPostProcessor
        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!
    // 不初始化FactoryBeans 下面是 BeanFactoryPostProcessor
    //0 = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
	//1 = "org.springframework.context.event.internalEventListenerProcessor"
	//2 = "propertySourcesPlaceholderConfigurer"
	//3 = "org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator"
	//4 = "preserveErrorControllerTargetClassPostProcessor"
    String[] postProcessorNames =
        beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    //按 order 分为三个集合,优先级order,普通order,没有order
    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);
    //调用 实现优先级order 的 bean 的
    // priorityOrderedPostProcessors = {PropertySourcesPlaceholderConfigurer@4157} 
    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);
    //调用 实现普通order 的 bean 的
    // orderedPostProcessors = {ConfigurationPropertiesBeanDefinitionValidator} 
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // Finally, invoke all other BeanFactoryPostProcessors.
    // 调用其他 BeanFactoryPostProcessors
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    //调用 没有实现order 的 bean 的
    //nonOrderedPostProcessors =  0 = {EventListenerMethodProcessor@4482} 
	// 1 = {ErrorMvcAutoConfiguration$PreserveErrorControllerTargetClassPostProcessor@4483} 
    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();
}

上面这个大方法主要做了两件事,调用所有 BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor 。

对于注解的扫描和处理,加载,注册,都在 org.springframework.context.annotation.ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry中。

其中BeanDefinitionRegistryPostProcessor 的有:

org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer.CachingMetadataReaderFactoryPostProcessor,
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer.ConfigurationWarningsPostProcessor,
org.springframework.context.annotation.ConfigurationClassPostProcessor

BeanFactoryPostProcessor 的有:

org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer.CachingMetadataReaderFactoryPostProcessor,
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer.ConfigurationWarningsPostProcessor,
org.springframework.context.annotation.ConfigurationClassPostProcessor

org.springframework.boot.context.config.ConfigFileApplicationListener.PropertySourceOrderingPostProcessor

org.springframework.context.support.PropertySourcesPlaceholderConfigurer
org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator
org.springframework.context.event.EventListenerMethodProcessor
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$PreserveErrorControllerTargetClassPostProcessor

按照 order 分为

priorityOrderedPostProcessors = PropertySourcesPlaceholderConfigurer
orderedPostProcessors = ConfigurationPropertiesBeanDefinitionValidator
nonOrderedPostProcessors = EventListenerMethodProcessor,ErrorMvcAutoConfiguration$PreserveErrorControllerTargetClassPostProcessor

你可能感兴趣的:(源码分析,SpringBoot源码分析,SpringBoot,刷新上下文,spring,boot,spring,java)