【Spring註解】@Condition條件註冊

3.@Condition條件註冊

@Condition來指定一定條件下注冊組件對像

All Conditions that must match in order for the component to be registered.

所有的條件必須實現Condition接口,重寫matches方法,來決定組件是否註冊


配置類

@Configuration
public class ConditionConfig {
    @Conditional(WindowsCondition.class)
    @Bean("bill")
    public Person bill(){
        return new Person("bill",10);
    }

    @Conditional(LinuxCondition.class)
    @Bean("Linus")
    public Person person(){
        return new Person("Linus",10);
    }
}

WindowsCondition 判斷windows環境

public class WindowsCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //獲取當前運行環境信息
        Environment environment = context.getEnvironment();
        //獲取當前環境名稱
        String osName = environment.getProperty("os.name");
        return osName.contains("Windows");
    }
}

LinuxCondition 判斷Linux環境

public class LinuxCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //獲取當前運行環境信息
        Environment environment = context.getEnvironment();
        //獲取當前環境名稱
        String osName = environment.getProperty("os.name");
        return osName.contains("Linux");
    }
}

測試(系統爲Window 7)

@Test
public void person() {
    Map<String, Person> beansOfType = annotationConfigApplicationContext.getBeansOfType(Person.class);
    System.out.println("beansOfType = " + beansOfType);
}

運行結果

設置vm的變量來模擬Linux環境,Run Configurations->VM options

添加 Dos.name=Linux

模擬Linux環境

運行結果

運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章