笨办法学习@ConditionalOnProperty 烧脑配置记录
前言
今天繼續學習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注解,能夠使代碼更加靈活。總結
以上是生活随笔為你收集整理的笨办法学习@ConditionalOnProperty 烧脑配置记录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 制作销售网络游戏外挂、网游辅助、脚本插件
- 下一篇: 归并排序示例