spring中@Conditional注解
@Conditional是Spring4新提供的注解,它的作用是根据某个条件加载特定的bean。
我们需要创建实现类来实现Condition接口,这是Condition的源码
public interface Condition { boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2); }
所以我们需要重写matches方法,该方法返回boolean类型。
首先我们准备根据不同的操作系统环境进行对容器加载不同的bean,先创建Person
public class Person { }
创建实现类LinuxCondition和WindowCondiction,
LinuxCondition:
public class WindowCondiction implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return true; } }
WindowCondiction:
public class LinuxCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return true; } }
配置类:给相应的bean加上 @Conditional注解,里面的括号将返回boolean类型,返回true则加载bean
@Configuration
public class MainConfig {
@Profile("window")
@Conditional(WindowCondiction.class)
@Bean
public Person person01(){
return new Person("李思",30);
}
@Profile("linux")
@Conditional(LinuxCondition.class)
@Bean
public Person person02(){
return new Person("wangwu",35);
}
}
测试:现在是按照linux环境,@Profile注解先匹配linux的bean,再根据@Conditional 返回的类型判断是否加载bean,这里都设置返回true,所以应该打印
Person{name='wangwu', age=35}
public class CondictionTest { @Test public void test(){ //创建容器 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); //设置需要激活的环境 applicationContext.getEnvironment().setActiveProfiles("linux"); //设置主配置类 applicationContext.register(MainProfileConfig.class); //启动刷新容器 applicationContext.refresh(); String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class); for (String name : beanNamesForType){ System.out.println(name); } applicationContext.close(); } }
如果把LinuxCondition的返回值该为false,会报找不到bean的异常
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springbean.Person' available