SpringBoot 條件註解解析

2021-09-02 01:39:28 字數 1464 閱讀 3825

當我們開發springboot專案時,有時候我們會根據不同的條件來建立相對應的bean物件,這個時候就用到了springboot自帶的條件註解,這裡我基於的springboot版本是 1.5.4.release

1、首先我們先定義乙個controller及其service介面

circulationcontroller

@restcontroller

public

class

circulationcontroller

}

icirculationservice

public

inte***ce

icirculationservice

2、再定義兩個實現類分別實現該service介面

forcirculationimpl

public

class

forcirculationimpl

implements

icirculationservice

}

foreachcirculationimpl

public

class

foreachcirculationimpl

implements

icirculationservice

}

3、第1步中,注入了乙個名為circulationservice的bean物件,這裡註冊該bean物件

circulationconfig

@configuration

public

class

circulationconfig

@bean

(name =

"circulationservice"

)@conditional

(forcondition.

class

)public icirculationservice getforcirculation()

}

4、定義@conditional註解所需的引數類,需要實現condition介面或繼承condition介面實現類

forcondition

public

class

forcondition

implements

condition

}

foreachcondition

public

class

foreachcondition

implements

condition

}

5、啟動專案,在瀏覽器中輸入 http://localhost:8080/test 進行測試

Spring Boot條件註解

一 為什麼springboot產生於spring4?spring4中增加了 condition annotation,使用該annotation之後,在做依賴注入的時候,會檢測是否滿足某個條件來決定是否注入某個類。conditional是springframework的功能,springboot在它...

springboot常見的條件依賴註解有

這些是springboot特有的,常見的條件依賴註解有 conditionalonbean,僅在當前上下文中存在某個bean時,才會例項化這個bean。conditionalonclass,某個class位於類路徑上,才會例項化這個bean。conditionalonexpression,當表示式為...

springboot 註解總結

springboot註解知識點歸納 當實現rest ful web services時,response將一直通過response body傳送。controller 用於定義控制器類,在spring 專案中由控制器負責將使用者發來的url請求 到對應的服務介面 service層 restcontr...