Spring 提供了按条件注册Bean的功能涉及到两个组件分别是:核心接口
Condition
,核心注解Conditional
。java
为了演示条件注解的效果,须要定义一个属性文件,而后根据属性文件中配置的值来加载符合这个值的组件。spring
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