SpringBoot開發實戰之自動配置

在介紹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,\
.....

太多瞭,有興趣的可以查看Spring的xxx-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才會進行自動加載並初始化。

總結

到此這篇關於SpringBoot開發實戰之自動配置的文章就介紹到這瞭,更多相關SpringBoot自動配置內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: