关于springboot:SpringBoot自动装配流程

35次阅读

共计 5041 个字符,预计需要花费 13 分钟才能阅读完成。

SpringBoot 重要的几个注解
SpringBootApplication 外面包含 EnableAutoConfiguration、SpringBootConfiguration、ComponentScan

EnableAutoConfiguration:启动主动拆卸
AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class) 主动拆卸导入类
ComponentScan:包扫描, 默认是启动类以后包

SpringBoot 启动 –SpringApplication.run(< 以后启动类 >,arg)– 以后主动类 (primarySource)–prepareContext() 容器事后初始化工作 –load 加载以后启动类
–refreshContext(相熟的 refresh 办法,Spring 容器创立以及初始化相干操作)– invokeBeanFactoryPostProcessors(beanFactory);
执行 BeanFactoryPostProcessors 办法
执行
invokeBeanFactoryPostProcessors 中重要一步 BeanDefinitionRegistryPostProcessor bean 定义信息处理器 实现类
ConfigurationClassPostProcessor(重要)实现了 postProcessBeanDefinitionRegistry
processConfigBeanDefinitions 配置 Bean 的定义信息
doProcessConfigurationClass 解析 Configuration 注解

processImports(configClass, sourceClass, getImports(sourceClass), true);
// 递归的解析配置类的注解 蕴含 import
private void collectImports(SourceClass sourceClass, Set<SourceClass> imports, Set<SourceClass> visited)
            throws IOException {if (visited.add(sourceClass)) {for (SourceClass annotation : sourceClass.getAnnotations()) {String annName = annotation.getMetadata().getClassName();
                if (!annName.equals(Import.class.getName())) {collectImports(annotation, imports, visited);
                }
            }
            imports.addAll(sourceClass.getAnnotationAttributes(Import.class.getName(), "value"));
        }
    }
    
/// 执行
this.deferredImportSelectorHandler.process();
    
    public void process() {
            List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
            this.deferredImportSelectors = null;
            try {if (deferredImports != null) {DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
                    deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
                    deferredImports.forEach(handler::register);
                    // 开始执行 Import 注解
                    handler.processGroupImports();}
            }
            finally {this.deferredImportSelectors = new ArrayList<>();
            }
        }

    }
// 执行办法    
public void processGroupImports() {for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {      // 这步
                grouping.getImports().forEach(entry -> {
                    ConfigurationClass configurationClass = this.configurationClasses.get(entry.getMetadata());
                    try {processImports(configurationClass, asSourceClass(configurationClass),
                                asSourceClasses(entry.getImportClassName()), false);
                    }
                    catch (BeanDefinitionStoreException ex) {throw ex;}
                    catch (Throwable ex) {
                        throw new BeanDefinitionStoreException(
                                "Failed to process import candidates for configuration class [" +
                                        configurationClass.getMetadata().getClassName() + "]", ex);
                    }
                });
            }
        }
// 下一步
public Iterable<Group.Entry> getImports() {for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {// 实现类     AutoConfigurationImportSelector            this.group.process(deferredImport.getConfigurationClass().getMetadata(),
                        deferredImport.getImportSelector());
            }
            return this.group.selectImports();}            

//AutoConfigurationImportSelector 实现类
@Override
        public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
            Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector,
                    () -> String.format("Only %s implementations are supported, got %s",
                            AutoConfigurationImportSelector.class.getSimpleName(),
                            deferredImportSelector.getClass().getName()));
            AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
// 获取         AutoConfigurationEntry            .getAutoConfigurationEntry(getAutoConfigurationMetadata(), annotationMetadata);
            this.autoConfigurationEntries.add(autoConfigurationEntry);
            for (String importClassName : autoConfigurationEntry.getConfigurations()) {this.entries.putIfAbsent(importClassName, annotationMetadata);
            }
        }
// 下一步 这步就开始清晰了
    protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
            AnnotationMetadata annotationMetadata) {if (!isEnabled(annotationMetadata)) {return EMPTY_ENTRY;}
        AnnotationAttributes attributes = getAttributes(annotationMetadata);
        // 主动拆卸开始
        List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
        configurations = removeDuplicates(configurations);
        Set<String> exclusions = getExclusions(annotationMetadata, attributes);
        checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = filter(configurations, autoConfigurationMetadata);
        fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationEntry(configurations, exclusions);
    }        
// getCandidateConfigurations 办法
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = 
//getSpringFactoriesLoaderFactoryClass 就是获取 EnableAutoConfiguration.class 这个主动拆卸类
//SpringFactoriesLoader    加载默认目录 META-INF/spring.factories 上面 加载主动拆卸 EnableAutoConfiguration 这种类型的 bean 此时加载的只是作为 bean 的定义信息    SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
                getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you"
                + "are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

加载 bean 的定义信息到 beanfactory 
接下来就是 Beanfactory 执行 bean 的生命周期流程    
                
                                

总结:SpringBoot 启动 SpringApplication.run 办法传入以后启动类 primarySources
加载以后配置类 在 refreshContext 中 invokeBeanFactoryPostProcessors 执行 BeanFactoryPostProcessors(ConfigurationClassPostProcessor) 加载那些主动配置的 bean 的定义信息、加载实现 执行后续的 beanfactory 创立 bean 的流程

正文完
 0