@Conditional注解的使用
条件判断注解Conditional
SpringBoot底层大量使用的注解
1. 注解的定义
由此可知需要实现condition接口
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
/**
* All {@link Condition} classes that must {@linkplain Condition#matches match}
* in order for the component to be registered.
*/
Class<? extends Condition>[] value();
}
2.使用步骤-->实现Condition接口
public class MyWindowsCondition implements Condition {
/**
* ConditionContext:判断条件能使用的上下文环境
* AnnotatedTypeMetadata:注释信息
*
* @param context
* @param metadata
* @return
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//1.获取IOC容器
BeanFactory beanFactory = context.getBeanFactory();
//2.获取类加载器
ClassLoader classLoader = context.getClassLoader();
//3.获取当前环境信息
Environment environment = context.getEnvironment();
//4.bean的注册
BeanDefinitionRegistry registry = context.getRegistry();
if (environment.getProperty("os.name").equals("Windows 10")) {
return true;
}
return false;
}
}
3.引入方式
@Bean
@Conditional({MyWindowsCondition.class})
public Dog dog3() {
return new Dog(1, "condition-->Dog-->windows");
}
4.当条件满足的时候就会将组件注入容器中
努力奔跑,是为了追上曾经被寄予厚望的自己。