Spring-boot中Conditional介绍

来源:互联网 发布:百度网盘会员 淘宝 编辑:程序博客网 时间:2024/06/09 18:28

原文地址:http://www.jianshu.com/p/0740c07f6c1d

@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注解来确定是否要加载该实例

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.
  1. ConditionalOnBean: 当且仅当指定的bean classes and/or bean names在当前容器中,才创建标记上该注解的类的实例
  2. ConditionalOnMissingBean: 当且仅当指定的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环境下创建

原创粉丝点击