欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring 配置文件字段注入到List、Map

 更新時(shí)間:2020年10月19日 10:23:26   作者:xiaowu6666  
這篇文章主要介紹了Spring 配置文件字段注入到List、Map,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

今天給大家分享冷門(mén)但是有很實(shí)小知識(shí),Spring 配置文件注入list、map、字節(jié)流。

list 注入

properties文件

user.id=3242,2323,1

使用spring el表達(dá)式

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

yaml 文件

在yml配置文件配置數(shù)組方式

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

雖然網(wǎng)上都說(shuō),這樣可以注入,我親身實(shí)踐過(guò)了,肯定是不能的。會(huì)拋出 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文件寫(xiě)法,使用el表達(dá)式即可

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()方法獲取流。比起使用類加載器獲取路徑再去加載文件的方式,優(yōu)雅、簡(jiǎn)單不少。

Map Key Value 注入

properties

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

成功注入

yaml

在yaml文件中,使用@Value不能注入Map 實(shí)例的,要借助@ConfigurationProperties 才能實(shí)現(xiàn)。

@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注入功能遠(yuǎn)比@Value強(qiáng),不僅能注入List、Map這些,還能注入對(duì)象屬性,靜態(tài)內(nèi)部類屬性,這個(gè)在Spring Boot Redis模塊  org.springframework.boot.autoconfigure.data.redis.RedisProperties體現(xiàn)出來(lái)。

區(qū)別

區(qū)別 @ConfigurationProperties @Value
類型 各種復(fù)制類型屬性Map、內(nèi)部類 只支持簡(jiǎn)單屬性
spEl表達(dá)式 不支持 支持
JSR303數(shù)據(jù)校驗(yàn) 支持 不支持
功能 一個(gè)列屬性批量注入 單屬性注入

到此這篇關(guān)于Spring 配置文件字段注入到List、Map的文章就介紹到這了,更多相關(guān)Spring 文件字段注入到List、Map內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論