spring按条件注入@Condition及springboot对其的扩展

概述

springioc极大的方便了日常开发,但随着业务的迭代。配置的一些参数在某些情况下需要按条件注入。

比如原先定义的db公共模块下,相关的配置和工具类只是基于mysql的。但是后续有模块需要使用mongo/es等其他数据库,又想继续使用db公共模块下的一些类。

那么这时候就希望db公共模块下可以根据classpath下的相关驱动class是否存在来自动注入相关类。

@Condition注解就能解决这个问题。这个注解是spring
org.springframework.context.annotation.Conditional

springboot的核心是习惯优于配置,所有现成的实现了一堆@Conditionxxxx注解,比如
org.springframework.boot.autoconfigure.condition.ConditionalOnBean
org.springframework.boot.autoconfigure.condition.ConditionalOnClass

@Condition

进到这个注解的源码中一看,发现核心是org.springframework.context.annotation.Condition
接口,里面就一个matches方法,返回true/false.
意思也很简单,true就是符合条件会被spring加载到ioc容器中false则不会.

matches方法的入参org.springframework.context.annotation.ConditionContext中可以拿到很多有用的信息

spring按条件注入@Condition及springboot对其的扩展_第1张图片
spring按条件注入@Condition及springboot对其的扩展_第2张图片

spring按条件注入@Condition及springboot对其的扩展_第3张图片

springboot内置现成的Condition实现类封装的注解

spring按条件注入@Condition及springboot对其的扩展_第4张图片

  1. @ConditionalOnSingleCandidate 当给定类型的bean存在并且指定为Primary的给定类型存在时,返回true
  2. @ConditionalOnMissingBean 当给定的类型、类名、注解、昵称在beanFactory中不存在时返回true.各类型间是or的关系
  3. @ConditionalOnBean 与上面相反,要求bean存在
  4. @ConditionalOnMissingClass 当给定的类名在类路径上不存在时返回true,各类型间是and的关系
  5. @ConditionalOnClass 与上面相反,要求类存在
  6. @ConditionalOnCloudPlatform 当所配置的CloudPlatform为激活时返回true
  7. @ConditionalOnExpression spel表达式执行为true
  8. @ConditionalOnJava 运行时的java版本号是否包含给定的版本号.如果包含,返回匹配,否则,返回不匹配
  9. @ConditionalOnProperty 要求配置属性匹配条件
  10. @ConditionalOnJndi 给定的jndiLocation 必须存在一个.否则,返回不匹配
  11. @ConditionalOnNotWebApplication web环境不存在时
  12. @ConditionalOnWebApplication web环境存在时
  13. @ConditionalOnResource 要求制定的资源存在

你可能感兴趣的:(springboot,spring,JAVA,spring,spring,boot,java)