Like Share Discussion Bookmark Smile

J.J. Huang   2019-03-17   Spring Boot   瀏覽次數:次   DMCA.com Protection Status

SpringBoot - 第七章 | 配置說明(二)

我們在 第六章 - SpringBoot配置說明(一) 已經大致介紹了基本的配置和使用方式;在這邊要說不同類型得屬性配置方式,例:List、Map、隨機亂數…等等。


隨機亂數

Spring Boot的配置文件中可以使用${random}来產生int、long或者string,來產生各種不同類型的隨機值。

1
2
3
4
5
6
com.jj.secret=${random.value}
com.jj.number=${random.int}
com.jj.bignumber=${random.long}
com.jj.uuid=${random.uuid}
com.jj.number.less.than.ten=${random.int(10)}
com.jj.number.int.range=${random.int[1024,65536]}
  • 撰寫RandomDemoController

啟動應用後,輸入http://localhost:8080/random ,就可以看到相對應的亂數值了。
secret:19d6199ca69e6d2efc7398efee9cb2b7
number:1010893841
bignumber:-6483113208442998425
uuid:bf3c714f-048e-42a7-8c3c-859cc22853d1
lessThanTen:2
range:36000
註:每次重新啟動應用,所取得的值基本上都會不一樣,達到隨機亂數的效果。


List類型

在properties文件中使用[]來表示List類型,或是利用逗號做表示

1
2
example.id[0]=A123456789
example.id[1]=B987654321
1
example.id=A123456789,B987654321

註:在Spring Boot 2.0中對於List類型的配置必須是連續的,不然會拋出UnboundConfigurationPropertiesException異常,所以如下配置是不允許的。

1
2
example.id[0]=A123456789
example.id[2]=B987654321

Map類型

Map類型在properties中的配置方式

1
example.pet.name={cat: 'princess', dog: 'prince'}
  • 撰寫ArrayDemoController

啟動應用後,輸入http://localhost:8080/list ,就可以看到”[A123456789, B987654321]”。
啟動應用後,輸入http://localhost:8080/map ,就可以看到”{cat=princess, dog=prince}”。