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
运行结果