Springboot注入帶參數的構造函數之兩種方式


教你如何使用Springboot注入帶參數的構造函數

我們使用@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之依賴構造器注入

看下面的例子,@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,這也表示以后不能再被更改了。

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

本文地址:https://www.linuxprobe.com/springboot-linux-service.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM