1. 程式人生 > 程式設計 >Spring 配置檔案欄位注入到List、Map

Spring 配置檔案欄位注入到List、Map

今天給大家分享冷門但是有很實小知識,Spring 配置檔案注入list、map、位元組流。

list 注入

properties檔案

user.id=3242,2323,1

使用spring el表示式

 @Value("#{'${user.id}'.split(',')}")
private List list;

yaml 檔案

在yml配置檔案配置陣列方式

number:
 arrays: 
  - One
  - Two
  - Three
@Value("${number.arrays}")
private List list

雖然網上都說,這樣可以注入,我親身實踐過了,肯定是不能的。會丟擲 Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'number.arrays' in value "${number.arrays}"異常。要想注入必須要使用

@ConfigurationProperties
@ConfigurationProperties(prefix = "number")
public class AgentController {

  private List arrays;
  public List getArrays() {
    return arrays;
  }

  public void setArrays(List arrays) {
    this.arrays = arrays;
  }
  @GetMapping("/s")
  public List lists(){
    return arrays;
  }

不是想這麼麻煩,可以像properties檔案寫法,使用el表示式即可

number:
 arrays: One,Two,Three
 @Value("#{'${number.arrays}'.split(',')}")
private List arrays;

注入檔案流

  @Value("classpath: application.yml")
  private Resource resource;
  
  // 佔位符
  @Value("${file.name}")
  private Resource resource2;

  @GetMapping("/s")
  public String lists() throws IOException {
    return IOUtils.toString(resource.getInputStream(),"UTF-8");
  }

從類路徑載入application.yml檔案將檔案注入到org.springframework.core.io.Resource ,可以使用getInputStream()方法獲取流。比起使用類載入器獲取路徑再去載入檔案的方式,優雅、簡單不少。

Map Key Value 注入

properties

resource.code.mapper={x86:"hostIp"}
 @Value("#{${resource.code.mapper}}")
private Map<String,String> mapper;

成功注入

yaml

在yaml檔案中,使用@Value不能注入Map 例項的,要藉助@ConfigurationProperties 才能實現。

@ConfigurationProperties(prefix = "blog")
public class AgentController {

  private Map website;

  public Map getWebsite() {
    return website;
  }

 public void setWebsite(Map website) {
    this.website = website;
  }

  @GetMapping("/s")
  public String lists() throws IOException {
    return JsonUtil.toJsonString(website);
  }

配置檔案

blog:
 website:
  juejin: https://juejin.im
  jianshu: https://jianshu.com
  sifou: https://segmentfault.com/

可以看出@ConfigurationProperties注入功能遠比@Value強,不僅能注入List、Map這些,還能注入物件屬性,靜態內部類屬性,這個在Spring Boot Redis模組 org.springframework.boot.autoconfigure.data.redis.RedisProperties體現出來。

區別

區別 @ConfigurationProperties @Value
型別 各種複製型別屬性Map、內部類 只支援簡單屬性
spEl表示式 不支援 支援
JSR303資料校驗 支援 不支援
功能 一個列屬性批量注入 單屬性注入

到此這篇關於Spring 配置檔案欄位注入到List、Map的文章就介紹到這了,更多相關Spring 檔案欄位注入到List、Map內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!