SpringBoot之配置

1. 自动配置原理

SpringBootApplication开始:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {}

SpringBootConfiguration

说明是SpringBoot的配置类

@Configuration
public @interface SpringBootConfiguration {}

@Configuration本身是@Component

EnableAutoConfiguration

主要有2个注解

@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
  • AutoConfigurationPackage

    它扫描主配置类SpringBootApplication同级目录以下所有的组件。

    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        AutoConfigurationPackages.register(registry, (String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArray(new String[0]));
    }
    

    getPackageNames()对应的就是主配置目录。

  • AutoConfigurationImportSelector

    ​ 加载自动配置类

    protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return EMPTY_ENTRY;
        } else {
            AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
            List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
            configurations = this.removeDuplicates(configurations);
            Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
            this.checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = this.getConfigurationClassFilter().filter(configurations);
            this.fireAutoConfigurationImportEvents(configurations, exclusions);
            return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
        }
    }
    
    • getAutoConfigurationEntry

    • getCandidateConfigurations

    • SpringFactoriesLoader.loadFactoryNames

      这里对应的是spring-boot-autoconfiguration下META-INF的spring.factories下org.springframework.boot.autoconfigure.EnableAutoConfiguration配置的autoconfiguration类。

ComponentScan

2. 配置的使用

  1. 配置文件

    yaml文件、properties文件2种方式

  2. 注入配置

    注入整个JavaBean:

    配置文件中的每一个属性的值,映射进一个组件中。perfix配置文件中那个属性

    ps:这个组件必须在容器中

    @Componet

    @ConfigurationProperties(prefix = "person")

    注入单条属性方式:

    @Value()

    可以是配置文件中属性,也可以用"#"注入表达时,还是可以环境变量。

  3. yaml中的自动提示

  4. springBootTest测试

# spring 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×