前言
今天继续学习springboot时,一不小心就被@ConditionalOnProperty注解的配置真假搞得我真的变得真真假假了。。(此为真,彼为假,到底你是真还是你是假,晕了晕了。。。)
本片主要记录一下注解的真假情况
源码
emmmm 先简单的翻译一下源码. 看每一个属性是什么含义.
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
/**
* name的别名
* Alias for {@link #name()}.
* @return the names
*/
String[] value() default {};
/**
* 应用于每个属性的前缀.如果前缀没有指定则以点结尾.一个有效的前
* 缀由一个或者多个用点分隔的单词组成(例: acme.system.feature)
* A prefix that should be applied to each property. The prefix automatically ends
* with a dot if not specified. A valid prefix is defined by one or more words
* separated with dots (e.g. {@code "acme.system.feature"}).
* @return the prefix
*/
String prefix() default "";
/**
* 需要验证的属性名, 如果一个前缀已经定义,则将其应用于一个完整的键
* 例如: 前缀app.config, 属性为: my-value, 则完整的键是app.config.my-value
* The name of the properties to test. If a prefix has been defined, it is applied to
* compute the full key of each property. For instance if the prefix is
* {@code app.config} and one value is {@code my-value}, the full key would be
* {@code app.config.my-value}
* <p>
* 使用虚线符来指定每个属性, 即全部小写, 并用"-"分割单词, 例如my-long-property
* Use the dashed notation to specify each property, that is all lower case with a "-"
* to separate words (e.g. {@code my-long-property}).
* @return the names
*/
String[] name() default {};
/**
* 属性的预期值, 如果未指定则改属性必须不等于false
* The string representation of the expected value for the properties. If not
* specified, the property must <strong>not</strong> be equal to {@code false}.
* @return the expected value
*/
String havingValue() default "";
/**
* 如果未指定属性, 则指定属性是否应匹配. 默认为false
* Specify if the condition should match if the property is not set. Defaults to
* {@code false}.
* @return if should match if the property is missing
*/
boolean matchIfMissing() default false;
}
验证
1、指定前缀及属性,但配置文件中不配置属性时
可以看到项目正常启动,没有进入创建User实例的方法
2、指定前缀及属性,配置文件中配置属性,但不指定havingValue值时
可以看到项目正常启动,并且进入了创建User实例的方法,因为havingValue默认为 “” 字符,并且指定属性后未在注解中指定havingValue,则与默认值进行比对,比对为真。
3、指定前缀及属性,配置文件中配置属性值,指定havingValue值
havingValue与属性值不同时:
havingValue与属性值相同时:
从上面看出,当havingValue配置的期望值与配置文件中的值相同则为真,反之则为假。为真时执行实例化方法,为假则不执行。
4、指定matchIfMissing时
matchIfMissing = true时
matchIfMissing = false时
可以看出来,当matchIfMissing为true时,不配置属性也会正常实例化bean。如果属性不指定,matchIfMissing指定为true匹配该属性是否进行匹配。当属性指定,且matchIfMissing也为true时,属性还是根据原有的规则进行校验。
反之: 如果matchIfMissing为true,不配置属性时,便不会实例化bean,相当于默认开启了属性校验。
结论
-
通过根据逻辑配置@ConditionalOnProperty注解的属性,来检查bean是否应该创建,将bean管理变为可插拔式。合理利用Conditional注解,能够使代码更加灵活。
- _ ~ 加油新的学习还在继续…