2018年4月29日 星期日

@Conditional (Spring 4.x 一)

依條件判斷,是否將某個 class 註冊到 bean 裡面
假設 java 版本是 1.7 就將 Animal 註冊;1.8 就將 Bird 註冊
@Conditional 可以寫在 Type 或是方法上



※寫在 Type

※條件

public class Java7Condition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String version = context.getEnvironment().getProperty("java.specification.version");
        if ("1.7".equals(version)) {
            return true;
        }
        return false;
    }
}
    
    
    
public class Java8Condition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String version = context.getEnvironment().getProperty("java.specification.version");
        if ("1.8".equals(version)) {
            return true;
        }
        return false;
    }
}



※使用

@Conditional(Java7Condition.class)
@Component
public class Animal {}
    
    
    
@Conditional(Java8Condition.class)
@Component
public class Bird {}



※測試

ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
for (String s : app.getBeanDefinitionNames()) {
    System.out.println(s);
}
app.close();

※可將 vm 參數改成需要的,按右鍵如下:






※寫在方法上



@Configuration
public class JavaVersionCondition {
    @Conditional(Java7Condition.class)
    @Bean
    public Animal a1() {
        Animal a = new Animal();
        a.setId(1);
        a.setName("tiger");
        return a;
    }
    
    @Conditional(Java7Condition.class)
    @Bean
    public Animal a2() {
        Animal a = new Animal();
        a.setId(2);
        a.setName("lion");
        return a;
    }
    
    @Conditional(Java8Condition.class)
    @Bean
    public Bird b1() {
        Bird b = new Bird();
        b.setId(3);
        b.setName("crow");
        return b;
    }
    
    @Conditional(Java8Condition.class)
    @Bean
    public Bird b2() {
        Bird b = new Bird();
        b.setId(4);
        b.setName("sparrow");
        return b;
    }
}

※是 java7 就有 a1、a2;是 java8 就有 b1、b2


※測試

// System.getProperties().list(System.out);
// System.out.println(app.getEnvironment().getProperty("java.specification.version"));
    
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Animal.class);
for (String s : app.getBeanDefinitionNames()) {
    System.out.println(s);
}
    
Map<String, Bird> type = app.getBeansOfType(Bird.class); // 取得 class 是 Bird 的 id 及內容
System.out.println(type);
    
for (String s : app.getBeanNamesForType(Bird.class)) { // 取得 class 是 Bird 的 id
    System.out.println(s);
}
app.close();



沒有留言:

張貼留言