您的位置:首頁技術文章
文章詳情頁

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

瀏覽:2日期:2023-05-20 17:07:50

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

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

@Configurationpublic 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; @Servicepublic class DatabaseCacheService implements CacheService { private final CacheManager cacheManager; @Autowired public DatabaseCacheService(CacheManager cacheManager) { this.cacheManager = cacheManager; } // ... }

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

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

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

以上這篇使用Springboot注入帶參數的構造函數實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
国产综合久久一区二区三区