标签:包含 override config 实体类 set bsp man style location
SpringBoot允许在外部进行配置,让你在不同的环境中运行相同的代码。你可以通过属性文件、YAML文件、环境变量和命令行来进行外部配置。属性值可以直接通过@Value注入,并可以通过Spring的Environment抽象类 或者 绑定了@ConfigurationProperties的实体类访问。
1、配置随机值。
RandomValuePropertySource在注入随机值时候非常有用(例如测试程序、加密程序中),它可以生成int、long、uuids和string等等。
my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int[1024,65536]}
2、命令行配置
默认情况下spring boot会转换命令行中的参数(以--开头,例如--server.port=9000)转换成Spring环境中的属性,命令行设置的属性值会覆盖其他地方配置的的属性值。
你可以通过设置SpringApplication.setAddCommandLineProperties(false)来禁用命令行配置。
3、应用属性文件
SrpingApplication会默认加载application.properties中的属性。这些属性文件可以放在 :
(1)当前目录的/config子目录。
(2)当前目录
(3)classpath下面的/config子目录。
(4)classpath根目录。
列表中后面位置文件属性会覆盖前面的。
如果你不喜欢application.properties,你通过改变spring.config.name来指定配置文件。也可以通过spring.config.location来指定多个文件(用逗号隔开),如下:
$ java -jar myproject.jar --spring.config.name=myproject
或
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
如果spring.config.location中包含文件夹(相对文件而言),它们必须以/结尾。
配置的搜索顺序从后到前,例如参数:classpath:/,classpath:/config/,file:./,file:./config/,则搜索顺序为
file:./config/ file:./ classpath:/config/ classpath:/
当自定义配置,它们会被添加到默认配置后面。它们会在默认配置的后面执行,例如自定义配置为classpath:/custom-config/,file:./custom-config/时,搜索顺序变成
file:./custom-config/ classpath:custom-config/ file:./config/ file:./ classpath:/config/ classpath:/
这些搜索顺序可以使得你在一个配置文件中指定配置顺序并能在另一个文件对其进行覆盖。
4、Profile-specific 属性文件
除了application.properties之外,可以通过命名为application-{profile}.properties的属性文件来定义属性。
profile-specific属性文件将会覆盖非profile-specific属性文件。
如果多个profile-specific属性文件被配置,则最后的一个会赢得决策。
如果你在spring.config.location中指定了任何配置文件,你的profile-specific属性文件将不会被考虑。除非你spring.config.location中仅仅指定了文件夹。
5、属性文件中的占位符
可以用EL表达式引用其他的值,如
app.name=MyApp
app.description=${app.name} is a Spring Boot application
标签:包含 override config 实体类 set bsp man style location
原文地址:http://www.cnblogs.com/qins/p/7529910.html