@Conditional注解可以根据自定义条件,选择符合条件的bean到IOC容器中。此注解被用来修饰配置类及其类中的方法。
1.修饰配置类时,表示配置类满足@Conditional注解的自定义条件时,配置类才会被容器加载,获取所需的bean,加入容器。
2.修饰配置类中的方法时:当配置类满足条件,配置类中方法若被@Conditional 注解修饰,满足注解的条件,执行此方法,否则不执行。
注解中条件设置通过其属性值xxx.java定义,xxx.java实现Conditon接口
案例:定义两个两个自定义类
1.自定义类LinuxCondition
若注解@Conditional的value值为LinuxCondition.class时:含义为当前系统是Linux时,被此注解修饰的配置类或其方法,将被容器引用
public class LinuxCondition implements Condition{
@Override
public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
//1.能获取到ioc使用的beanFactory
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//2.获取类加载器
ClassLoader classLoader = context.getClassLoader();
//3.获取当前环境信息
Environment environment = context.getEnvironment();
//4.获取注册类
BeanDefinitionRegistry registry = context.getRegistry();
String property = environment.getProperty("os.name");
if (property.contains("linux")) {
return true;
}
return false;
}
}
2.自定义类WindowsConditon:
若注解@Conditional的value值为WindowsConditon.class时:当前系统是Windows时,被此注解修饰的类或方法,将被容器引用
public class WindowsConditon 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;
}
}
3.编制配置类MainConfig2.java
MainConfig2.java被@Conditional({WindowsConditon.class})注解修饰时,表示系统为window时,容器才能调用配置类 。
方法person01()被 @Conditional({LinuxCondition.class})注释修饰时,表示当前系统为Linux时,bean才能被加载到容器中
/**
*若当前操作系统为window时,配置类中方法才能被调用
*/
@Conditional({WindowsConditon.class})
@Configuration
public class MainConfig2 {
@Bean(value="person")
public Person person(){
System.out.println("给容器中添加Person....");
return new Person("Lily",18);
}
@Bean("bill")
public Person person01(){
return new Person("Bill Gates", 62);
}
//@Conditional:按照一定的条件进行判断,慢足条件给容器中注册bean
@Conditional({LinuxCondition.class})
@Bean("linus")
public Person person02(){
return new Person("linus",48);
}
@Bean
public ColorFactoryBean colorFactoryBean(){
return new ColorFactoryBean();
}
}
4.测试案例
@Test
public void test03(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("os.name");
System.out.println("当前使用系统:"+property);
//引用对象
Map<String, Person> persons = applicationContext.getBeansOfType(Person.class);
System.out.println(persons);
}
运行结果:
当前使用系统:Windows 7
{person=Person [name=Lily, age=18], bill=Person [name=Bill Gates, age=62]}