Spring高階裝配 二 條件化的bean

2021-09-08 14:07:48 字數 1910 閱讀 5799

如果你希望乙個bean在特定的條件下才會出現:

在spring 4之前,很難實現這種級別的條件化配置,但是spring4引入了乙個新的@conditional註解,它可以用到帶有@bean註解的方法上。如果給定的條件計算結果為true,就會建立這個bean,否則的話,這個bean會被忽略。

示例:設定了magic環境屬性才去例項化magicbean

1

@bean

2 @conditional(magicexistscondition.class) //

條件化地建立bean

3public

magicbean magicbean()

這裡的@conditional中給定了乙個class,它指明了條件,也就是magiccondition。

condition介面如下:

1

public

inte***ce

condition

設定給@conditional的類可以使任意實現了condition介面的型別。如此一來,只需要提供matches( )方法的實現即可。如果matches( )方法返回為true,那麼就會建立帶有@conditional註解的bean。反之則不會建立這些bean。

magicexistscondition的實現:

1

public

class magicexistscondition implements

condition

6 }

上面的例子中只獲取了environment,conditioncontext中的內容還挺豐富的,它是乙個介面:

1

public

inte***ce

conditioncontext

通過conditioncontext,可以拿到的資源有:

annotationedtypemetadata則能夠讓我們檢查帶有@bean註解的方法上還有什麼其他註解。

1

public

inte***ce

annotatedtypemetadata

通過isannotated方法,我們能夠判斷帶有@bean註解的方法是不是還有其他特定的註解。借助其他的方法,能夠檢查@bean註解的方法上其他註解的屬性。

在spring 4開始,@profile註解進行了重構,使其基於@conditional和condition的實現。

在spring 4中@profile的實現如下:

1

@retention(retentionpolicy.runtime)

2@target()

3@documented

4 @conditional()

5public @inte***ce

profile

profilecondition:

1

class profilecondition implements

condition 11}

12return

false;13

}14}15

return

true;16

}17 }

profilecondition通過annotatedtypemetadata得到了用於@profile註解的所有屬性。借助該資訊,它會明確地檢查value屬性,該屬性包含了bean的profile名稱。然後根據conditioncontext得到的environment來檢查(借助acceptsprofiles()方法)該profile是否處於啟用狀態。

MySQL高階二 條件查詢

目錄 where 語法 執行順序 分類 1 按條件表示式篩選 2 按邏輯表示式篩選 3 模糊查詢 1 like 2 between and 3 in 4 is null 5 完全等於 該教程使用mysql5.5.27以及sqlyog安裝教程請參考mysql和sqlyog安裝教程 select 查詢列...

二 條件迴圈語句

1 查詢那些既可以被7整除又可以被5整除的數字,介於1500和2700之間 1 使用列表推導式 num i for i in range 1500 2700 if i 7 0and i 5 0 print num out 1505,1540,1575,1610,1645,1680,1715,1750...

python初學二 條件語句

1.句法 one way decision if two way decision if else multiway decision if elif else 2.try.except 語句 異常處理 如果try後的語句出現執行錯誤 程式會執行except後的語句 在執行try中的語句時在那條語句...