@Conditional 注解

@Conditional 注解是进行条件判断的, 满足当前条件,就加载 bean,否则不加载。

@Conditional 的属性

value 传入一个 Condition 的配置类


实现效果: 当前系统为 Windows 我们就打印 张三 为 Linux 系统就打印 李四


Person 类

public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Condition 条件类
Windows Condition 类

public class WindowsCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String osName = context.getEnvironment().getProperty("os.name");
        System.out.println(osName);
        return osName.contains("Windows");
    }
}

// 实现的 Condition 接口是 Spring 的包下的

Linux Condition 类

public class LinuxCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String osName = context.getEnvironment().getProperty("os.name");
        System.out.println(osName);
        return osName.contains("Linux");
    }
}

配置类

@Configuration
public class ConditionalConfig {

    @Conditional(WindowsCondition.class)
    @Bean("zhangsan")
    public Person person01() {
        return new Person("张三-Windows 系统", 40);
    }

    @Conditional(LinuxCondition.class)
    @Bean("lisi")
    public Person person02() {
        return new Person("李四 - Linux", 60);
    }

}


测试类

    @Test
    public void test6() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(ConditionalConfig.class);
        Person person = ctx.getBean(Person.class);
        String[] names = ctx.getBeanNamesForType(Person.class);
        for (String name : names) {
            System.out.println(name);
        }
        System.out.println(person);
    }

结果


没有 lisi

Windows 10 被打印两次,说明 Linux Condition 也走了,但是代码判断没有通过。
下面运行时,通过指定启动时的虚拟机参数,修改系统,看看结果

修改启动参数方法


修改启动参数
Linux打印结果

你可能感兴趣的:(@Conditional 注解)