Spring Boot 神奇的自动配置,主要依靠大量的条件注解来使用配置自动化。
根据满足某一个特定条件创建一个特定的Bean。比如说,在某些系统变量下创建Bean,或者只有在某个Bean创建后才去创建另外一个Bean. 就是根据条件来控制Bean的创建行为,可以利用该特性来进行一些自动配置。
比较常见的是这些注解,还有其它的比如 @ConditionalOnWebApplication, @ConditionalOnProperty 等,可举一反三
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Conditional { /** * All {@link Condition Conditions} that must {@linkplain Condition#matches match} * in order for the component to be registered. */ Class<? extends Condition>[] value(); } 复制代码
使用@Conditional注解,对象需要实现Condition接口,Condition 接口是一个函数式接口
@FunctionalInterface public interface Condition { boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata); } 复制代码
示例场景:项目中动态的配置Mysql或者Oracle数据源
db-type=oracle 复制代码
MySqlCondition.java
public class MySqlCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return "mysql".equals(context.getEnvironment().getProperty("db-type")); } } 复制代码
OracleCondition.java
public class OracleCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return "oracle".equals(context.getEnvironment().getProperty("db-type")); } } 复制代码
获取配置文件db-type的值
public interface JdbcFactory { void create(); } 复制代码
Mysql
@ConditionalOnMissingBean(value = JdbcFactory.class, ignored = MySqlDefaultFactory.class) @Conditional(MySqlCondition.class) @Component public class MySqlDefaultFactory implements JdbcFactory { @Override public void create() { System.out.println("Default MySql create .."); } } 复制代码
Oracle
@ConditionalOnMissingBean(value = JdbcFactory.class, ignored = OracleDefaultFactory.class) @Conditional(OracleCondition.class) @Component public class OracleDefaultFactory implements JdbcFactory { @Override public void create() { System.out.println("Default oracle create.."); } } 复制代码
@Resource private JdbcFactory jdbcFactory; @Test public void conditionOnMissBean() { jdbcFactory.create(); } 复制代码
结果:
Default MySql create .. 复制代码
@Component public class MysqlFactory implements JdbcFactory { @Override public void create() { System.out.println("mysql 。。 create"); } } 复制代码
@Resource private JdbcFactory jdbcFactory; @Test public void conditionOnMissBean() { jdbcFactory.create(); } 复制代码
结果:
mysql 。。 create 复制代码