注解源码
@Conditional注解源码
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
/**
* All {@link Condition}s that must {@linkplain Condition#matches match}
* in order for the component to be registered.
*/
Class<? extends Condition>[] value();
}
我们可以看到这个注解:value值传的是实现了Condition这个接口的类的数组
Condition接口源码
@FunctionalInterface
public interface Condition {
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
使用举例
现在有两个bean: bill 和 linus ,现在我们想按照操作系统的不同来选择是否在IOC容器里面注册bean:
现在下面的两个bean注册到IOC容器是要条件的:
- 如果系统是windows,给容器注册(“bill”)
- 如果系统是linux,给容器注册(“linus”)
实现condition接口
/**
* 判断操作系统是否为Linux系统
*/
public class LinuxCondition implements Condition {
/**
* ConditionContext : 判断条件能使用的上下文(环境)
* AnnotatedTypeMetadata : 注释信息
* @return
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//判断是否为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");
if (property.contains("linux")) {
return true;
}
return false;
}
}
/**
* 判断操作系统是否为Windows系统
*/
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//3.能获取当前环境的信息
Environment environment = context.getEnvironment();
//获取操作系统
String property = environment.getProperty("os.name");
if (property.contains("Windows")) {
return true;
}
return false;
}
}
当两个条件写好了之后,我们给容器注册bean就可以写了:
@Configuration
public class MainConfig2 {
/**
* @Conditional:是SpringBoot底层大量使用的注解,按照一定的条件来进行判断,满足条件 给容器注册bean
*/
/**
* 现在下面的两个bean注册到IOC容器是要条件的:
* 1.如果系统是windows,给容器注册("bill")
* 1.如果系统是linux,给容器注册("linus")
* @return
*/
@Conditional({WindowsCondition.class})
@Bean("bill")
public Person person01() {
return new Person("Bill Gates",62);
}
@Conditional({LinuxCondition.class})
@Bean("linus")
public Person person02() {
return new Person("linus",48);
}
}
@Conditional 的这个注解还可以标注在类上,对容器中的组件进行统一设置:满足当前条件,这个类中配置的所有bean注册才能生效
@Configuration
//满足当前条件,这个类中配置的所有bean注册才能生效
@Conditional({WindowsCondition.class})
public class MainConfig2 {
/**
* @Conditional:是SpringBoot底层大量使用的注解,按照一定的条件来进行判断,满足条件 给容器注册bean
*/
/**
* 现在下面的两个bean注册到IOC容器是要条件的:
* 1.如果系统是windows,给容器注册("bill")
* 1.如果系统是linux,给容器注册("linus")
* @return
*/
@Bean("bill")
public Person person01() {
return new Person("Bill Gates",62);
}
@Conditional({LinuxCondition.class})
@Bean("linus")
public Person person02() {
return new Person("linus",48);
}
}