Springboot中怎么注入帶參數(shù)的構(gòu)造函數(shù)

本篇文章給大家分享的是有關(guān)Springboot中怎么注入帶參數(shù)的構(gòu)造函數(shù),小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話(huà)不多說(shuō),跟著小編一起來(lái)看看吧。

我們提供的服務(wù)有:網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、沿灘ssl等。為上千余家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢(xún)和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的沿灘網(wǎng)站制作公司

使用@Configuration+ @Bean注解來(lái)實(shí)現(xiàn)注入:

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

service類(lèi)

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

補(bǔ)充知識(shí):Spring Boot - Spring Beans之依賴(lài)構(gòu)造器注入

使用所有Spring Framework技術(shù)定義的beans以及他們的依賴(lài)注入都是免費(fèi)的。簡(jiǎn)單起見(jiàn),我們通常使用@CompnentScan查找beans,結(jié)合@Autowired構(gòu)造注入效果比較好。

如果你的代碼結(jié)構(gòu)是按之前建議的結(jié)構(gòu)(將應(yīng)用類(lèi)放到根包里),你可以添加@ComponentScan,不需要任何參數(shù)。這樣你所有的應(yīng)用組件(@Component,@Service,@Repository,@Controller等等)都將會(huì)注冊(cè)為Spring Beans。

看下面的例子,@Service Bean使用構(gòu)造注入,獲取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;
 }
  
 // ...
  
}

如果這個(gè)bean有一個(gè)構(gòu)造,可以省略@Autowired。

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

以上就是Springboot中怎么注入帶參數(shù)的構(gòu)造函數(shù),小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

新聞標(biāo)題:Springboot中怎么注入帶參數(shù)的構(gòu)造函數(shù)
分享地址:http://www.muchs.cn/article42/ghgsec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊(cè)、虛擬主機(jī)、定制開(kāi)發(fā)搜索引擎優(yōu)化、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、外貿(mào)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)