SpringBoot的自動配置

懵懂小虎發表於2021-08-11

在介紹SpringBoot的自動配置之前,先了解下註解@Import的使用,SpringBoot@Enable*開頭的註解底層依賴於@Import註解匯入一些類,使用@Import匯入的類會被Spring載入到IOC容器中,而@Import提供了以下4中用法:

  • 直接匯入Bean
  • 通過配置類匯入Bean
  • 匯入ImportSelector實現類,一般用於載入配置檔案的類
  • 匯入ImportBeanDefinitionRegistrar實現類

下面來分別介紹這幾種用法。

  • 直接匯入Bean就比較簡單了,新建一個User
public class User{
    private String name;
    private String address;
}

然後在啟動類上使用@Import註解匯入即可

@SpringBootApplication
@Import(User.class)
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
        System.out.println(context.getBean(User.class));
    }
}

這裡需要注意的是,通過上下文獲取Bean時,需要使用Bean的class,因為通過Bean的方式匯入,Spring存入IOC容器,是用類的全類名儲存的。可以使用上下文的getBeansOfType方法檢視,返回的是Map物件。

{com.tenghu.sbc.entity.User=User(name=null, age=0)}

從返回的結果可以看出,key就是存的User的全類名。

  • 通過配置類匯入Bean,建立一個配置類;
public class UserConfig {
    @Bean(name = "user")
    public User user(){
        return new User();
    }
}

然後通過@Import匯入這個配置類

@SpringBootApplication
@Import(UserConfig.class)
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
        System.out.println(context.getBean(User.class));
    }
}

通過配置類的方式可以在配置類裡面定義多個Bean,當匯入配置類時,配置類下定義的Bean都會被匯入。

  • 匯入ImportSelector實現類
public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{User.class.getName()};
    }
}

實現ImportSelector類,必須實現selectImports,然後返回需要匯入的Bean。與上面一樣使用@Import匯入這個實現類。

@Import(MyImportSelector.class)
  • 匯入ImportBeanDefinitionRegistrar實現類
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(User.class).getBeanDefinition();
        registry.registerBeanDefinition("user",beanDefinition);
    }
}

使用方式一樣,通過@Import匯入

@Import(MyImportBeanDefinitionRegistrar.class)

瞭解完@Import的使用,接下來可以來看下SpringBoot的自動配置是怎麼處理的。從上面的啟動類,使用SpringBoot就用了一個註解@SpringBootApplication,可以開啟這個註解的原始碼看下:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication

用到這樣一個註解@EnableAutoConfiguration註解。底層使用@Import匯入上面第三種方式AutoConfigurationImportSelector

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

進入原始碼找到實現了selectImports方法

public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    } else {
        AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
    }
}

通過呼叫方法getAutoConfigurationEntry

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);
    }
}

這裡主要的看呼叫這個方法getCandidateConfigurations,返回的就是要自動載入的Bean

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
}

通過META-INF/spring.factories配置檔案裡的EnableAutoConfiguration獲取配置的Bean

# 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,\
.....

太多了,有興趣的可以檢視Springxxx-autoconfigure包。將讀取到的配置最終返回給selectImports,然後通過工具類StringUtils.toStringArray轉換為字串陣列返回給@Import,從而實現自動配置。第三方包只要是xxx-autoconfigure結尾的包,META-INF都有spring.factories,這個名字是固定寫法。都可以被SpringBoot識別並且進行自動配置,前提是需要配置到org.springframework.boot.autoconfigure.EnableAutoConfiguration下。
從以上總結來看,SpringBoot的自動配置原理如下:

  • @EnableAutoConfiguration註解內部使用Import(AutoConfigurationImportSelector.class)來載入配置類
  • 通過配置檔案:META-INF/spring.factories,配置大量的配置類,SpringBoot啟動時就會自動載入這些類並初始化的Bean

這裡需要說明一點,並不是所有配置到配置檔案的Bean都會被初始化,需要符合配置類中使用Condition來載入滿足條件的Bean。比如我們開啟RedisAutoConfiguration的原始碼檢視:

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

類上面有這麼個註解@ConditionalOnClass({RedisOperations.class}),意思就是需要RedisOperations類存在的情況下,才自動載入;這還不算完,繼續檢視下面的方法上有個@ConditionalOnMissingBean(name = {"redisTemplate"}),這裡的意思是,當其他地方沒有redisTemplate例項化這個Bean時,才自動載入。符合這兩個條件,SpringBoot才會進行自動載入並初始化。

相關文章