SpringBoot使用自动配置xxxAutoConfiguration

SpringBoot使用自动配置xxxAutoConfiguration 常用的类: @ConditionalOnProperty(name = use.redis.session.store, havingValue = true) @ConditionalOnClass(Session.class) @AutoConfigureAfter(RedisAutoConfiguration.class) @ConditionalOnWebApplication @ConditionalOnMissingBe

常用的类:

  • @ConditionalOnProperty(name = "use.redis.session.store", havingValue = "true")
  • @ConditionalOnClass(Session.class)
  • @AutoConfigureAfter(RedisAutoConfiguration.class)
  • @ConditionalOnWebApplication
  • @ConditionalOnMissingBean(RedisHttpSessionConfiguration.class)
  • @SpringBootApplication(exclude ={SessionAutoConfiguration.class})

举例:以MybatisAutoConfiguration为例

  • 1. 在jar包中/META-INF/spring.factories中配置
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
    spring在启动时会去自动加载这个bean
  • 2. MybatisAutoConfiguration.java上加上@Configuration
  • 3. 如果需要通过自定义构造函数来构造bean,则加上构造函数

public MybatisAutoConfiguration(MybatisProperties properties,
                                  ObjectProvider<Interceptor[]> interceptorsProvider,
                                  ResourceLoader resourceLoader,
                                  ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                  ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider) {
    this.properties = properties;
    this.interceptors = interceptorsProvider.getIfAvailable();
    this.resourceLoader = resourceLoader;
    this.databaseIdProvider = databaseIdProvider.getIfAvailable();
    this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
}

构造函数中依赖的Bean,Spring会自动从Spring beanFactory容器中去找到适配的bean来传入

参数:

  • MybatisProperties properties --> 依赖MybatisProperties 这个bean,而MybatisProperties 是一个@ConfigurationProperties。则加上@EnableConfigurationProperties(MybatisProperties.class),让bean MybatisProperties 先加载
  • ObjectProvider<Interceptor[]> interceptorsProvider --> 依赖 org.apache.ibatis.plugin.Interceptor[],但又不确定 Interceptor 的bean是否存在,则通过ObjectProvider<Interceptor[]> 去获取,interceptorsProvider.getIfAvailable()
  • ResourceLoader resourceLoader --> 依赖 bean ResourceLoader,直接在 Spring 容器中找到相应的 bean
  • ObjectProvider<DatabaseIdProvider> databaseIdProvider --> 同上
  • ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider --> 同上

附:断点打在MybatisAutoConfiguration 的构造函数上,查看调用栈,便可以看出端倪

以上所述是小编给大家介绍的SpringBoot使用自动配置xxxAutoConfiguration,希望对大家有所帮助。在此也非常感谢大家对我们网站的支持!

本文标题为:SpringBoot使用自动配置xxxAutoConfiguration

基础教程推荐