Spring Boot 2.0 新特性(一):配置绑定 2.0 全解析
作者:媒体转发 时间:2018-06-01 09:01
在Spring Boot 2.0中推出了Relaxed Binding 2.0,对原有的属性绑定功能做了非常多的改进以帮助我们更容易的在Spring应用中加载和读取配置信息。下面本文就来说说Spring Boot 2.0中对配置的改进。

配置文件绑定
简单类型
在Spring Boot 2.0中对配置属性加载的时候会除了像1.x版本时候那样移除特殊字符外,还会将配置均以全小写的方式进行匹配和加载。所以,下面的4种配置方式都是等价的:
properties格式:
spring.jpa.databaseplatform=mysql
spring.jpa.database-platform=mysql
spring.jpa.databasePlatform=mysql
spring.JPA.database_platform=mysql
yaml格式:
spring:
jpa:
databaseplatform: mysql
database-platform: mysql
databasePlatform: mysql
database_platform: mysql
Tips:推荐使用全小写配合-分隔符的方式来配置,比如:spring.jpa.database-platform=mysql
List类型
在properties文件中使用[]来定位列表类型,比如:
spring.my-example.url[0]=http://example.com
spring.my-example.url[1]=http://spring.io
也支持使用逗号分割的配置方式,上面与下面的配置是等价的:
spring.my-example.url=http://example.com,
而在yaml文件中使用可以使用如下配置:
spring:
my-example:
url:
-
-
也支持逗号分割的方式:
spring:
my-example:
url: ,
注意:在Spring Boot 2.0中对于List类型的配置必须是连续的,不然会抛出UnboundConfigurationPropertiesException异常,所以如下配置是不允许的:
foo[0]=a
foo[2]=b
在Spring Boot 1.x中上述配置是可以的,foo[1]由于没有配置,它的值会是null
Map类型
Map类型在properties和yaml中的标准配置方式如下:
properties格式:
spring.my-example.foo=bar
spring.my-example.hello=world
yaml格式:
spring:
my-example:
foo: bar
hello: world
注意:如果Map类型的key包含非字母数字和-的字符,需要用[]括起来,比如:
spring:
my-example:
'[foo.baz]': bar
环境属性绑定
简单类型
在环境变量中通过小写转换与.替换_来映射配置文件中的内容,比如:环境变量SPRING_JPA_DATABASEPLATFORM=mysql的配置会产生与在配置文件中设置spring.jpa.databaseplatform=mysql一样的效果。
List类型
由于环境变量中无法使用[和]符号,所以使用_来替代。任何由下划线包围的数字都会被认为是[]的数组形式。比如:
MY_FOO_1_ = my.foo[1]
MY_FOO_1_BAR = my.foo[1].bar
MY_FOO_1_2_ = my.foo[1][2]
另外,最后环境变量最后是以数字和下划线结尾的话,最后的下划线可以省略,比如上面例子中的第一条和第三条等价于下面的配置:
MY_FOO_1 = my.foo[1]
MY_FOO_1_2 = my.foo[1][2]
系统属性绑定
简单类型
系统属性与文件配置中的类似,都以移除特殊字符并转化小写后实现绑定,比如下面的命令行参数都会实现配置spring.jpa.databaseplatform=mysql的效果:
-Dspring.jpa.database-platform=mysql
-Dspring.jpa.databasePlatform=mysql
-Dspring.JPA.database_platform=mysql
List类型
系统属性的绑定也与文件属性的绑定类似,通过[]来标示,比如:
-D"spring.my-example.url[0]=http://example.com"
-D"spring.my-example.url[1]=http://spring.io"
同样的,他也支持逗号分割的方式,比如:
-Dspring.my-example.url=http://example.com,
属性的读取



