天天看點

SpringBoot 重新整理上下文1--主流程1、獲得BeanFactory2、初始化IOC

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<org.springframework.beans.factory.config.BeanFactoryPostProcessor>)
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 = {[email protected]}  size = 3
		// 0 = {SharedMetadataReaderFactoryCon[email protected]} 
		// 1 = {ConfigurationWarningsApplica[email protected]} 
		// 2 = {[email protected]} 
        //調用 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 = {[email protected]}  size = 3
		// 0 = {SharedMetadataReaderFactoryCon[email protected]} 
		// 1 = {ConfigurationWarningsApplica[email protected]} 
		// 2 = {[email protected]} 
        //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 = {[email protected]} 
    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 = {[email protected]} 
	// 1 = {ErrorMvcAutoConf[email protected]} 
    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