SpringBoot AutoConfigure原理

2018-09-12  本文已影响331人  自负的鱼

SpringBoot AutoConfigure原理

外化配置和自动配置

将配置从代码中分离到XML或者properties中,这种spring配置外部化的方式成为外部配置。
spring 自动配置,spring-boot-autoconfigure依赖默认配置项,根据添加的依赖自动加载相关的配置属性并启动依赖。应用者只需要引入对应的start jar包,spring boot 就可以自动扫描和加载依赖信息。

自动配置原理

自动配置的前提

SpringBoot 的 AutoConfiguration

SpringBoot通过@EnableAutoConfiguration开启自动配置,借助SpringFactoriesLoader将所有符合自动配置条件的bean定义加载到IOC容器。

   @Target({ElementType.TYPE})
   @Retention(RetentionPolicy.RUNTIME)
   @Documented
   @Inherited
   @AutoConfigurationPackage
   @Import({EnableAutoConfigurationImportSelector.class})
   public @interface EnableAutoConfiguration {
       String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
   
       Class<?>[] exclude() default {};
   
       String[] excludeName() default {};
   }
```
public class AutoConfigurationImportSelector
        implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
        BeanFactoryAware, EnvironmentAware, Ordered {
    //通过select加载自动配置信息
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        }
        try {
          // Step1: 得到注解信息
            AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
                    .loadMetadata(this.beanClassLoader);
            // Step2: 得到注解中的所有属性信息
            AnnotationAttributes attributes = getAttributes(annotationMetadata);
            // Step3: 得到候选配置列表
            List<String> configurations = getCandidateConfigurations(annotationMetadata,
                    attributes);
            // Step4: 去重
            configurations = removeDuplicates(configurations);
            // Step5: 排序
            configurations = sort(configurations, autoConfigurationMetadata);
            // Step6: 根据注解中的exclude信息去除不需要的
            Set<String> exclusions = getExclusions(annotationMetadata, attributes);
            checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = filter(configurations, autoConfigurationMetadata);
            // Step7: 派发事件
            fireAutoConfigurationImportEvents(configurations, exclusions);
            return configurations.toArray(new String[configurations.size()]);
        }
        catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }
}
```

在步骤三中加载依赖的Configurations

```
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
        AnnotationAttributes attributes) {
    List<String> configurations = 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;
}
```
   public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
       String factoryClassName = factoryClass.getName();
       try {
           Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                   ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
           List<String> result = new ArrayList<String>();
           while (urls.hasMoreElements()) {
               URL url = urls.nextElement();
               Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
               String factoryClassNames = properties.getProperty(factoryClassName);
               result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
           }
           return result;
       }
       catch (IOException ex) {
           throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
                   "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
       }
   }
   # Auto Configure
   org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
   org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
   org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
   org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
   org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
   org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
   org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
   org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
   ....

AutoConfiguration自定义Starter

通过spring-boot-autoconfigure完成自动化配置自定义starter。starter让我们摆脱了各种依赖库的处理,需要配置各种信息的困扰。Spring Boot会自动通过classpath路径下的类发现需要的Bean,并织入bean。

添加META-INF/spring.factories

在src/main/resources资源目录下创建META-INF/spring.factories 配置文件,在该文件中配置key和value。
其中key固定为:org.springframework.boot.autoconfigure.EnableAutoConfiguration

配置自定义Autoconfigure

自定义Autoconfigure文件负责设置自动加载规则和条件,只有在引用start项目中符合条件是才回自动装配。

/**
 * 该配置文件需要在spring.factories中引入
 * 在SpringBoot启动台的时候通过SpringFactoriesLoader会加载项目中spring.factories文件
 *
 * 配置自动装载器
 */
@Configuration
@EnableConfigurationProperties({AutoConfiguraionProperties.class})
@ConditionalOnClass({CompanyStarterService.class})
@ConditionalOnProperty(prefix="company.starter",name = "enable",havingValue = "true")
public class AutoStarterConfiguration {

    private AutoConfiguraionProperties properties;

    public AutoStarterConfiguration(AutoConfiguraionProperties properties){
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean(CompanyStarterService.class)
    public CompanyStarterService companyStarterService(){
        return new CompanyStarterService(this.properties);
    }

}

@ConfigurationProperties配置项映射

对于自动装配中需要使用的配置项,可以通过自定义@ConfigurationProperties的方式从application.yml中获取配置内容。

/**
 * 自定义starter的application配置映射文件
 * 可以将application.properies或者application.yml中属性映射到java类
 */
@Data
@ConfigurationProperties(prefix = "company.starter")
public class AutoConfiguraionProperties {

    private String host;

    private Integer port;

}

在Autoconfigure中通过@Bean 配置IOC容器加载类

通过@Bean 配置来决定哪些类可以自动装配到IOC容器,并在系统中使用

@Bean
@ConditionalOnMissingBean(CompanyStarterService.class)
public CompanyStarterService companyStarterService(){
    return new CompanyStarterService(this.properties);
}
上一篇下一篇

猜你喜欢

热点阅读