这篇文章主要介绍了SpringBoot自动装配Condition的实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
1. 简介
@Conditional注解在Spring4.0中引入,其主要作用就是判断条件是否满足,从而决定是否初始化并向容器注册Bean。
2. 定义
2.1 @Conditional
@Conditional
注解定义如下:其内部只有一个参数为Class对象数组,且必须继承自Condition
接口,通过重写Condition
接口的matches
方法来判断是否需要加载Bean
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Conditional { Class[] valu<b style="color:transparent">来源gao@dai!ma.com搞$代^码网</b>e(); }
2.2 Condition
Condition
接口定义如下:该接口为一个函数式接口,只有一个matches
接口,形参为ConditionContext context, AnnotatedTypeMetadata metadata
。ConditionContext
定义如2.2.1
,AnnotatedTypeMetadata
见名知意,就是用来获取注解的元信息的
@FunctionalInterface public interface Condition { boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata); }
2.2.1 ConditionContext
ConditionContext
接口定义如下:通过查看源码可以知道,从这个类中可以获取很多有用的信息
public interface ConditionContext { /** * 返回Bean定义信息 * Return the {@link BeanDefinitionRegistry} that will hold the bean definition * should the condition match. * @throws IllegalStateException if no registry is available (which is unusual: * only the case with a plain {@link ClassPathScanningCandidateComponentProvider}) */ BeanDefinitionRegistry getRegistry(); /** * 返回Bean工厂 * Return the {@link ConfigurableListableBeanFactory} that will hold the bean * definition should the condition match, or {@code null} if the bean factory is * not available (or not downcastable to {@code ConfigurableListableBeanFactory}). */ @Nullable ConfigurableListableBeanFactory getBeanFactory(); /** * 返回环境变量 比如在application.yaml中定义的信息 * Return the {@link Environment} for which the current application is running. */ Environment getEnvironment(); /** * 返回资源加载器 * Return the {@link ResourceLoader} currently being used. */ ResourceLoader getResourceLoader(); /** * 返回类加载器 * Return the {@link ClassLoader} that should be used to load additional classes * (only {@code null} if even the system ClassLoader isn't accessible). * @see org.springframework.util.ClassUtils#forName(String, ClassLoader) */ @Nullable ClassLoader getClassLoader(); }
3. 使用说明
通过一个简单的小例子测试一下@Conditional
是不是真的能实现Bean的条件化注入。
3.1 创建项目
首先我们创建一个SpringBoot项目
3.1.1 导入依赖
这里我们除了springboot依赖,再添加个lombok依赖
4.0.0 org.springframework.bootspring-boot-starter-parent2.5.3<!-- lookup parent from repository -->com.ldxcondition0.0.1-SNAPSHOTconditionDemo project for Spring Boot 1.8 org.springframework.bootspring-boot-starter org.projectlomboklombok1.18.12 org.springframework.bootspring-boot-maven-plugin
3.1.2 添加配置信息
在application.yaml 中加入配置信息
user: enable: false
3.1.3 创建Us
以上就是SpringBoot自动装配Condition的实现方式的详细内容,更多请关注gaodaima搞代码网其它相关文章!