常用的类:
@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.MybatisAutoConfigurationspring在启动时会去自动加载这个bean2. MybatisAutoConfiguration.java上加上@Configuration
3. 如果需要通过自定义构造函数来构造bean,则加上构造函数
public MybatisAutoConfiguration(MybatisProperties properties, ObjectProviderinterceptorsProvider, ResourceLoader resourceLoader, ObjectProvider databaseIdProvider, ObjectProvider
> 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 容器中找到相应的 beanObjectProvider<DatabaseIdProvider> databaseIdProvider --> 同上ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider --> 同上
附:断点打在MybatisAutoConfiguration 的构造函数上,查看调用栈,便可以看出端倪