【Spring 系列 条件注解】

Spring 提供了按条件注册Bean的功能涉及到两个组件分别是:核心接口Condition,核心注解Conditionaljava

一、示例说明

为了演示条件注解的效果,须要定义一个属性文件,而后根据属性文件中配置的值来加载符合这个值的组件。spring

二、定义一个属性配置文件和POJO

gender=girl
public class Foo {
    String gender;
    public Foo(String gender) {
        this.gender = gender;
    }
    @Override
    public String toString() {
        return "Foo{" +
                "gender='" + gender + '\'' +
                '}';
    }
}

三、新增两个接口实现类

public class GirlCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String gender = context.getEnvironment().getProperty("gender");
        return "girl".equalsIgnoreCase(gender);
    }
}
public class BoyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String gender = context.getEnvironment().getProperty("gender");
        return "boy".equalsIgnoreCase(gender);
    }
}

四、新增一个配置类

@Configuration
@PropertySource({"classpath:app.properties"})
public class ExampleConfiguration {
    @Bean
    @Conditional(BoyCondition.class)
    public Foo boy() {
        return new Foo("男");
    }
    @Bean
    @Conditional(GirlCondition.class)
    public Foo girl() {
        return new Foo("女");
    }
}

使用@PropertySource()加载外部配置文件。shell

五、测试

public class ExampleApplication {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExampleConfiguration.class);
        Arrays.asList(context.getBeanDefinitionNames()).forEach(System.out::println);
    }
}

六、运行结果

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
exampleConfiguration
girl

能够看出由于配置文件中配置的gender=girl因此容器只加载了girl组件。能够经过修改配置文件的值来查看具体效果。app

七、总结说明

@Conditional通常配和Condition一块儿使用,只有接口返回true,才装配,不然不装配。 当@Conditional做用在方法上那么只对该方法生效,也能够做用在类上,则对类的全部的属性或者方法都适用。 而且能够在一个类或者方法上能够配置多个,只有当接口所有返回true才会生效。ide

相关文章
相关标签/搜索