@Conditional注解

docker-blog / 2023-07-29 / 原文

1.介绍@Conditional注解

@Conditional注解源码

@Conditionl注解简单说明

@Conditional注解所属包
org.springframework.context.annotation.Conditional
注解作用范围
{ElementType.TYPE, ElementType.METHOD}
类、接口、注解、枚举以及 方法
注解生命周期
@Retention(RetentionPolicy.RUNTIME)
代码编译为.class文件后,注解仍然存在,而且能被虚拟机识别,可以通过反射获取到

2.@Conditional注解的用法

Indicates that a component is only eligible for registration when all specified conditions match.

仅当所有条件被满足时组件才有资格被注册进容器中

The @Conditional annotation may be used in any of the following ways:

1.as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes

2.as a meta-annotation, for the purpose of composing custom stereotype annotations

3.as a method-level annotation on any @Bean method

@Conditional注解可能用在以下这些场景中

1.作为一个type级别的注解,在任何被@Component注解包括@Configuration注解注解或者间接修饰的类上使用;

2.作为元注释,用于组合自定义构造型注释

3.作为method级别注解在任何被@Bean修饰的方法上

If a @Configuration class is marked with @Conditional, all of the @Bean methods, @Import annotations, and @ComponentScan annotations associated with that class will be subject to the conditions.

如果@Configuration类被标记为@Conditional,那么与该类关联的所有@Bean方法、@Import注解和@ComponentScan注解都将受这些条件的约束。

 3.代码用例

创建类A,B,C以及TestCondition

class A extends AllNestedConditions {
    public A() {
        super(ConfigurationPhase.REGISTER_BEAN);
    }

    public A(ConfigurationPhase configurationPhase) {
        super(configurationPhase);
    }

    @ConditionalOnMissingBean(value = {C.class})
    static class B{
    }
}
public class B {
}
@Component
public class C {
}
@Configuration
public class TestCondition {

    @Bean
    @Conditional(value = {A.class})
    public B b(){
        System.out.println("B注入了!");
        return new B();
    }
}

当C被注入到容器中时,@Conditional注解满足条件,B就被注入到容器中

当C不@Component注解时,@Conditional注解不满足条件,B无法被注入到容器中