@Conditional的做用域:java
1. 類級別能夠放在註標識有@Component(包含@Configuration)的類上linux
2. 做爲一個meta-annotation,組成自定義註解spring
3. 方法級別能夠放在標識由@Bean的方法上windows
3.1版本的spring 其實提供了profile,在spring4中能夠使用@profile註解。ide
若是一個@Configuration的類標記了@Conditional,全部標識了@Bean的方法和@Import註解導入的相關類將聽從這些條件。操作系統
condition接口定義以下:code
public interface Condition{ /** Determine if the condition matches. * @param context the condition context * @param metadata meta-data of the {@link AnnotationMetadata class} or * {@link Method method} being checked. * @return {@code true} if the condition matches and the component can be registered * or {@code false} to veto registration. */ boolean matches(ConditionContext context, AnnotatedTypeMedata metadata); }
若是要使用這個註解,須要實現這個接口,並重寫matches方法,其實就是寫規則。component
看一個demo:接口
import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class LinuxCondition implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Linux"); } }
import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class WindowsCondition implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Windows"); } }
咱們有兩個類LinuxCondition 和WindowsCondition 。兩個類都實現了Condtin接口,重載的方法返回一個基於操做系統類型的布爾值。作用域
下面咱們定義兩個bean,一個符合條件另一個不符合條件:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfiguration { @Bean(name="emailerService") @Conditional(WindowsCondition.class) public EmailService windowsEmailerService(){ return new WindowsEmailService(); } @Bean(name="emailerService") @Conditional(LinuxCondition.class) public EmailService linuxEmailerService(){ return new LinuxEmailService(); } }
這樣寫完之後,當項目啓動時,會先從系統環境變量讀取 os.name的值,來判斷到底應該加載哪個bean。