• 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.
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    调了本类的refresh

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

    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);
    
                ...
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

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

    1、获得BeanFactory

    //org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        return getBeanFactory();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    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());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

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

    创建BeanFactory的逻辑在构造器。

    public GenericApplicationContext() {
        this.beanFactory = new DefaultListableBeanFactory();
    }
    
    • 1
    • 2
    • 3

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

    1.2、获得BeanFactory

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

    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()));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    调用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();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182

    上面这个大方法主要做了两件事,调用所有 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

  • 相关阅读:
    Prometheus+Grafana监控系统
    数据分析笔试题(二)
    [vulnhub] Matrix:1
    allegro中shape的一些基本操作(一)——添加和修改shape
    [4G/5G/6G专题基础-156]: 什么是物理层信道评估
    SAP的MIGO移动类型
    A tour of gRPC:01 - 基础理论
    剑指 Offer 25. 合并两个排序的链表
    自动化测试 | 测试老鸟总结,你们项目自动化测试实施成功与否的因素
    计算机毕设(附源码)JAVA-SSM家纺商品展示平台
  • 原文地址:https://blog.csdn.net/xuwenjingrenca/article/details/126574225