歡迎您光臨本站 註冊首頁

使用Springboot注入帶參數的構造函數實例

←手機掃碼閱讀     niceskyabc @ 2020-05-01 , reply:0

我們使用@Service註解一個service,默認注入的是不帶參的構造函數,如果我們需要注入帶參的構造函數,怎麼辦?

使用@Configuration+ @Bean註解來實現注入:

@Configuration public class BlockChainServiceConfig { @Bean BlockChainService blockChainService(){ return new BlockChainService(1); } }

service類

public class BlockChainService { private int number; public BlockChainService(int number) { this.number=number; } }

補充知識:Spring Boot - Spring Beans之依賴構造器注入

使用所有Spring Framework技術定義的beans以及他們的依賴注入都是免費的。簡單起見,我們通常使用@CompnentScan查找beans,結合@Autowired構造注入效果比較好。

如果你的代碼結構是按之前建議的結構(將應用類放到根包裡),你可以添加@ComponentScan,不需要任何參數。這樣你所有的應用組件(@Component,@Service,@Repository,@Controller等等)都將會註冊為Spring Beans。

看下面的例子,@Service Bean使用構造注入,獲取CacheManager bean。

package com.example.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DatabaseCacheService implements CacheService { private final CacheManager cacheManager; @Autowired public DatabaseCacheService(CacheManager cacheManager) { this.cacheManager = cacheManager; } // ... }

如果這個bean有一個構造,可以省略@Autowired。

@Service public class DatabaseCacheService implements CacheService { private final CacheManager cacheManager; public DatabaseCacheService(CacheManager cacheManager) { this.cacheManager = cacheManager; } // ... }

注意,使用構造注入允許cacheManager標記為final,這也表示以後不能再被更改了。


[niceskyabc ] 使用Springboot注入帶參數的構造函數實例已經有238次圍觀

http://coctec.com/docs/java/show-post-232451.html