@Conditional():按照一定的条件进行判断,满足条件给容器中注册bean,可以标注在类上和方法上
代码:
第一步:创建一个配置类
@Configuration
public class Config {
@Conditional(WindowsCondition.class)
@Bean
public Person person1() {
return new Person("凯莎", 20);
}
@Conditional(LinuxCondition.class)
@Bean
public Person person2() {
return new Person("卡尔", 22);
}
}
第二部:创建需要条件的系统类
//判断是否linux系统
public class LinuxCondition implements Condition {
/**
* ConditionContext:判断条件能使用的上下文(环境)
* AnnotatedTypeMetadata:注释信息
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// TODO是否linux系统
// 1、能获取到ioc使用的beanfactory
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 2、获取类加载器
ClassLoader classLoader = context.getClassLoader();
// 3、获取当前环境信息
Environment environment = context.getEnvironment();
// 4、获取到bean定义的注册类
BeanDefinitionRegistry registry = context.getRegistry();
String property = environment.getProperty("os.name");
// 可以判断容器中的bean注册情况,也可以给容器中注册bean
boolean definition = registry.containsBeanDefinition("person");
if (property.contains("linux")) {
return true;
}
return false;
}
}
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String property = environment.getProperty("os.name");
if (property.contains("Windows")) {
return true;
}
return false;
}
}
第三步:测试
@Test
public void testConditional() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
String[] nameType = applicationContext.getBeanNamesForType(Person.class);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
// 动态获取环境变量的值;Windows 10
String property = environment.getProperty("os.name");
System.out.println(property);
for (String name : nameType) {
System.out.println(name);
}
Map<String, Person> persons = applicationContext.getBeansOfType(Person.class);
System.out.println(persons);
}
结果:
Windows 7
{person1=Person [name=凯莎, age=20, nickName=null]}