spring-boot学习笔记之Conditional

@Conditional

官方文档定义:“Indicates that a component is only eligible for registration when all specified conditions match”,意思是只有满足一些列条件之后创建一个bean。
@Conditional定义

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Conditional {
    Class<? extends Condition>[] value();
}

@Conditional注解主要用在以下位置:

  • 类级别可以放在注标识有@Component(包含@Configuration)的类上
  • 作为一个meta-annotation,组成自定义注解
  • 方法级别可以放在标识由@Bean的方法上
spring-boot的@Conditional系列

spring-boot利用Conditional来确定是不是要创建Bean实例,如下是官方的说明,大概是说boot是启用@Conditional注解来确定是否要加载该实例
<blockquote>No. Boot is enabled in Spring Framework 4.0 by the @Conditional annotation infrastructure. Your perception of loaded is accurate otherwise - JRebel is much more comprehensive, works with multiple IDEs, etc. </blockquote>

  1. ConditionalOnBean: 当且仅当指定的bean classes and/or bean names在当前容器中,才创建标记上该注解的类的实例
  2. ConditionalOnBean: 当且仅当指定的bean classes and/or bean names不存在当前容器中,才创建标记上该注解的类的实例,有指定忽略ignored的参数存在,可以忽略Class、Type等
  3. ConditionalOnClass:当且仅当ClassPath存在指定的Class时,才创建标记上该注解的类的实例
  4. ConditionalOnMissingClass:当且仅当ClassPath不存在指定的Class时,创建标记上该注解的类的实例
  5. ConditionalOnProperty:当且仅当Application.properties存在指定的配置项时,创建标记上了该注解的类的实例
  6. ConditionalOnJava:指定JDK的版本
  7. ConditionalOnExpression:表达式用${..}=false等来表示
  8. ConditionalOnJndi:JNDI存在该项时创建
  9. ConditionalOnResource:在classpath下存在指定的resource时创建
  10. ConditionalOnSingleCandidate:Conditional
    that only matches when the specified bean class is already contained in the BeanFactory
    and a single candidate can be determined.The condition will also match if multiple matching bean instances are already contained in the BeanFactory
    but a primary candidate has been defined; essentially, the condition match if auto-wiring a bean with the defined type will succeed.
  11. ConditionalOnWebApplication:在web环境下创建
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容