您可以自由地使用任何標准的Spring Framework技術來定義bean及其注入的依賴項。為簡單起見,我們經常發現使用 @ComponentScan
(找到你的bean)並使用 @Autowired
(做構造函數注入)效果很好。
如果按照上面的建議構建代碼(在根包中定位應用程序類),則可以添加 @ComponentScan
而不帶任何參數。所有應用程序組件( @Component
, @Service
, @Repository
, @Controller
等)都會自動注冊為Spring Beans。
以下示例顯示了一個 @Service
Bean,它使用構造函數注入來獲取所需的 RiskAssessor
bean:
package com.example.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DatabaseAccountService implements AccountService { private final RiskAssessor riskAssessor; @Autowired public DatabaseAccountService(RiskAssessor riskAssessor) { this.riskAssessor = riskAssessor; } // ... }
覺得有幫助的可以支持一下博主
