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