一、前言
本文承接上一节:Spring_总结_04_高级配置(一)之Profile
在上一节,我们了解到 Profile 为不同环境下使用不同的配置提供了支持,那么Profile到底是如何实现的呢?其实Profile正是通过条件注解来实现的。
条件注解的应用场景举例:
(1)希望一个或多个 bean 只有在应用的类路径下包含特定的库时才创建
(2)希望某个bean只有当另外某个特定bean也声明了之后才创建
(3)希望只有某个特定的环境变量设置之后,才会创建某个bean
上述场景能让我们联想到springboot的自动化配置、Profile以及配置文件等。
二、概述
1.定义
@Conditionnal 能根据特定条件来控制Bean的创建行为。
2.用法
@Conditional注解可以用到带有@Bean注解的方法上,如果给定的条件计算结果为true,就会创建这个bean,否则,忽略这个bean。
3.用处
可以用来进行一些自动化配置,如上述三个应用场景。
三、使用实例
1.创建Condition实现类
Condition接口如下,只有一个 matches 方法,用来判断是否满足条件。
@FunctionalInterface public interface Condition { /** * Determine if the condition matches. * @param context the condition context * @param metadata metadata of the {@link org.springframework.core.type.AnnotationMetadata class} * or {@link org.springframework.core.type.MethodMetadata method} being checked * @return {@code true} if the condition matches and the component can be registered, * or {@code false} to veto the annotated component's registration */ boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata); }