基本類型的使用
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: ...
...