SpringBoot 自動配置
@SpringBootApplication解釋引導加載自動配置類
//@SpringBootApplication 等同于下面3個注解
@SpringBootConfiguration // 就是一個@Configuration注解,代表當前是一個配置類
@EnableAutoConfiguration
//指定掃描哪些,Spring注解;
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public class Application
{
public static void main( String[] args )
{
SpringApplication.run(Application.class, args);
}
}
1.@SpringBootApplication
等同于3個注解@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan
1.1@SpringBootConfiguration
就是一個@Configuration注解,代表當前是一個配置類
1.2@ComponentScan
指定掃描哪些,Spring注解
1.3@EnableAutoConfiguration
包含如下兩個注解
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
a. @AutoConfigurationPackage``
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}
//@AutoConfigurationPackage用@Import引入Registrar.class 利用Registrar類的兩個方法
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
Registrar() {
}
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
}
public Set<Object> determineImports(AnnotationMetadata metadata) {
return Collections.singleton(new AutoConfigurationPackages.PackageImport(metadata));
}
}
new AutoConfigurationPackages.PackageImport(metadata)拿到的就是包名
就可以匯入包名下一系列標注的的組件 也就是通過這個方法 約定主函式要和
其他包處于同級目錄下才能掃描到組件

b.@Import({AutoConfigurationImportSelector.class})
使用getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata)批量的匯入一些組件
再用List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes)
獲取到所有需要匯入到容器中的配置類
呼叫 List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader())
利用loadFactoryNames工廠加載Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader)
得到所有的組件
從META-INF/spring.factories位置來加載一個檔案,
默認掃描我們當前系統里面所有META-INF/spring.factories位置的檔案
spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories
檔案里面寫死了spring-boot一啟動就要給容器中加載的所有配置類
spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories
然后再按需開啟自動配置項
xxxxAutoConfiguration
按照條件裝配規則(@Conditional),最侄訓按需配置
List configurations 獲取到的候選的配置類一共有125個

總結
SpringBoot先加載所有的自動配置類 xxxxxAutoConfiguration
每個自動配置類按照條件進行生效,默認都會系結組態檔指定的值,xxxxProperties里面拿,xxxProperties和組態檔進行了系結
生效的配置類就會給容器中裝配很多組件
只要容器中有這些組件,相當于這些功能就有了
定制化配置
用戶直接自己@Bean替換底層的組件
用戶去看這個組件是獲取的組態檔什么值就去修改,
xxxxxAutoConfiguration —> 組件 —> xxxxProperties里面拿值 ----> application.properties
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/290859.html
標籤:java
