Java SpringBoot 讀取、使用yaml文件類型的簡(jiǎn)述,和對(duì)集合list的使用解析

基本類型的使用

yml文件大部分使用的都是字符串,如果想使用其它類型,只要直接按其它類型寫變量值就可以了。
舉例:

#使用boolean
my-switch:
 is-on: true

Java中使用只要加上@Value就可以了:

@Value("${my-switch.is-on}")
private boolean switchOn;

使用其它類型也是一樣的。


集合的使用

舉例:

#使用int的list
student:
 ids: [1, 2, 3, 4, 5]

或者:

#使用int的list
student:
 ids: 
  - 1
  - 2
  - 3
  - 4
  - 5

這個(gè)時(shí)候要注意了,Java如果直接寫成:

@Value("${student.id}")
private List<Integer> ids;

啟動(dòng)時(shí)會(huì)報(bào)錯(cuò),Cannot resolve placeholder 什么的
這時(shí)候應(yīng)該新建一個(gè)對(duì)list屬性的配置類:

@Configuration
@ConfigurationProperties("student")
public class PropertyConfig{
  private List<Integer> ids;
  // getter & setter
}

然后在要使用的地方自動(dòng)注入,調(diào)用一個(gè)getter方法就可以得到配置文件中的值。


yml文件還可以存放對(duì)象和對(duì)象的集合,使用方法與基本類型類似。
簡(jiǎn)單舉例:

#使用對(duì)象
student:
  id: 1
  name: Bruce
  gender: male
#使用對(duì)象集合
students: 
  - id: 1
    name: Bruce
    gender: male
  - id: 2
    name: ...
    ...
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容