package org.springframework.boot.autoconfigure.condition;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.context.annotation.Conditional;@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE, ElementType.METHOD})@Documented@Conditional({OnPropertyCondition.class})public @interface ConditionalOnProperty {/*** 该属性与下面的 name 属性不可同时使用,* 当value所对应配置文件中的值为false时,注入不生效,不为fasle注入生效* value有多个值时,只要有一个值对应为false,则注入不成功*/String[] value() default {};/*** 配置文件中key的前缀,可与value 或 name 组合使用*/String prefix() default "";/*** 与 value 作用一致*/String[] name() default {};/*** 与value 或 name 组合使用,只有当value 或 name 对应的值与havingValue的值相同时,注入生效*/String havingValue() default "";/*** 该属性为true时,配置文件中缺少对应的value或name的对应的属性值,也会注入成功*/boolean matchIfMissing() default false;}
@Component@EnableScheduling@ConditionalOnProperty(name = "timer.enabled")public class ConditionalOnPropertyTest {private static Logger logger = LogManager.getLogger(ConditionalOnPropertyTest.class);@Scheduled(cron = "*/5 * * * * ?")public void test(){logger.info("定时器执行....");}}
各种配置结果如下:
timer.enabled=false //无效timer.enabled=true //有效timer.enabled=1111 //有效timer.enabled=null //有效
@ConditionalOnProperty(value = "timer.enabled")
如果同时配置了name属性和value属性,我们试试看
@ConditionalOnProperty(value = "timer.open", name = "timer.enabled")
结果启动报错:
Caused by: java.lang.IllegalStateException: The name and value attributes of @ConditionalOnProperty are exclusive
@ConditionalOnProperty(prefix = "timer", name = "enabled")
作用和把name直接命名为:timer.enabled一样,prefix可以和name或者value属性组合使用,用.连接,那么一般为了方便管理,通常都会用多层级的方式进行组合,下面都统一用前缀组合的方式进行分析
4、havingValue属性
下面介绍havingValue属性,即只有当name或者value属性的值与havingValue属性完全相同时,注入才有效,示例如下:
@ConditionalOnProperty(prefix = "timer", name = "enabled",havingValue = "open")
timer.enabled=open
@ConditionalOnProperty(prefix = "timer", name = "enabled",havingValue = "open",matchIfMissing = true)
结果如下:
timer.enabled=333 //无效timer.enabled=open //有效不配置 //有效
通过上面的讲解,详细大家对这四个属性的作用已经非常清楚了。
6、name或者value为多个值的情况
@ConditionalOnProperty(prefix = "timer", name = {"enabled","isopen"},havingValue = "open")这就要求name的两个值都必须有并且为open
timer.enabled=open //只有一个无效timer.enabled=opentimer.isopen=open //有效timer.enabled=opentimer.isopen=111 //无效不配置 //无效
如果加上matchIfMissing属性,表示可以缺少
@ConditionalOnProperty(prefix = "timer", name = {"enabled","isopen"},havingValue = "open",matchIfMissing = true)不配置 //有效timer.enabled=open //有效timer.enabled=opentimer.isopen=open //有效timer.enabled=opentimer.isopen=111//无效timer.enabled=111//无效
转自源代码社区