@Conditional 按照一定的条件进行判断,满足条件给容器注册bean
参数为class对象的数组
传入的类要实现Condition接口
package com.zyc.spring.condition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
//判断是否是windows
public class WindowsCondition implements Condition {
/**
* ConditionContext 判断条件能使用的上下文
* AnnotatedTypeMedatata 注释信息
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// TODO Auto-generated method stub
//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");
if(property.contains("Windows")){
return true;
}
return false;
}
}
package com.zyc.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import com.zyc.spring.bean.Person;
import com.zyc.spring.condition.LinuxCondition;
import com.zyc.spring.condition.WindowsCondition;
@Configuration
public class MainConfig2 {
@Bean("person")
//@Scope("prototype")
public Person person(){
System.out.println("容器中添加Person");
return new Person();
}
@Conditional({WindowsCondition.class})
@Bean("bill")
public Person person1(){
return new Person("bill",1);
}
@Conditional({LinuxCondition.class})
@Bean("linux")
public Person person2(){
return new Person("linux",22);
}
}
测试类
@Test
public void test2(){
AnnotationConfigApplicationContext con = new AnnotationConfigApplicationContext(MainConfig2.class);
ConfigurableEnvironment enviroment = con.getEnvironment();
String property = enviroment.getProperty("os.name");
String[] beanNamesForType = con.getBeanNamesForType(Person.class);
for(String name : beanNamesForType){
System.out.println(name);
}
Map<String,Person> persons = con.getBeansOfType(Person.class);
System.out.println(persons);
}