@Conditional

作用

  根据特定条件来控制Bean的创建行为,比如说只有某个Bean被创建才会创建另外一个Bean。

使用

  @Conditional元数据为实现Condition接口类的集合,matches返回true则创建Bean。可以使用在类型和方法上,与其它创建Bean的注解配合使用。

  • 类型级别,可以在@Component 或是 @Configuration类上使用;
  • 方法级别,可以用在@Bean的方法上;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

    /**
     * All {@link Condition}s that must {@linkplain Condition#matches match}
     * in order for the component to be registered.
     */
    Class<? extends Condition>[] value();

}
@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);

}

解析器

参考:

  1. https://segmentfault.com/a/1190000011033012
  2. http://blog.longjiazuo.com/archives/1351

猜你喜欢

转载自blog.csdn.net/yangguosb/article/details/80868627