前言
@conditional
中文意思为有条件的。的确它也是干这事的。
@Conditional
是 Spring4 提供的注解,作用是按照指定的条件进行判断,满足所有条件候选Bean才会向容器注册。
源码定义
@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();
}
复制代码
该注解可以在类、方法上标注。注解中就一个 value
属性,值为继承Condition
的接口的数组。
Condition
接口定义如下:
@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);
}
复制代码
Condition
是一个函数式接口,因此可以用 lambda 表达式或方法引用为目标赋值。实现 Condition
接口,需要重写