在 《springboot-自动化配置》 中讲解了 springboot 自动化配置原理。
一、案例需求
日常开发中,存在有共享 jar 依赖,当项目引用该 依赖时,会对已经配置好的配置类进行自动配置,使得配置能够重复利用,简化配置。
二、官方说明
Under the hood, auto-configuration is implemented with standard
@Configurationclasses. Additional@Conditionalannotations are used to constrain when the auto-configuration should apply. Usually auto-configuration classes use@ConditionalOnClassand@ConditionalOnMissingBeanannotations. This ensures that auto-configuration only applies when relevant classes are found and when you have not declared your own@Configuration. You can browse the source code of spring-boot-autoconfigure to see the@Configurationclasses that we provide (see theMETA-INF/spring.factoriesfile).
大体翻译如下:
1、自动配置类继承自标准的 注解
@Configuration。 2、通过@Conditional,进行驱动,而通常的@Conditional驱动,主要为@ConditionalOnClass和@ConditionalOnMissingBean。这两个注解保证了在你没有显示声明配置的时候,实现自动注入的功能 3、我们可以在spring-boot-autoconfigure中找到相关的自动配置类。 4、这些配置类,其实主要根据我声明定义的META-INF/spring.factories进行查找。
通过官方对于自动配置的先关说明能够得出自定义一个自动配置类的步骤
- 1、定义配置文件,并加上注解
@Configuration - 2、在
META-INF/spring.factories中配置定义好的配置文件的全路径名
在以上两种操作下,还可以通过使用 @Conditional 类的驱动,对自动配置类进行更灵活的配置。
如: @ConditionalOnMissingBean的组合配置
@Configuration@ConditionalOnMissingBean(DistributedTransactionAutoConfig.class)public class DistributedTransactionAutoConfig {}
当 DistributedTransactionAutoConfig 未被配置时,才会进行配置,否则可能导致冲突。
三、实现
项目结构如下
模式一
引用依赖,启动应用程序,直接进行自动配置
step1、定义自动配置类
例如:
@Configuration@ConditionalOnMissingBean(DistributedTransactionAutoConfig.class)public class DistributedTransactionAutoConfig {@Beanpublic DistributedTransactionBean distributedTransactionBean(){return new DistributedTransactionBean();}}
step2、在 META-INF 下的 spring.factories 中配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.xxx.auto.config.mode1.DistributedTransactionAutoConfig
模式二
引用依赖,需要通过注解的方式才能够开启(开启开关,如@EnableXXX)
step1、定义自动配置类
例如:
public class DistributedLockAutoConfig {@Beanpublic DistributedLockBean distributedLockBean(){return new DistributedLockBean();}}
step2、定义 @EnableXXX 注解(通过 @Import 实现)
例如:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Import(DistributedLockAutoConfig.class)public @interface EnableLock {}
