SpringBoot配置文件详解

自定义属性与加载

com.dongk.selfproperty.title=wangdk
com.dongk.selfproperty.name=10000

然后通过@Value("${属性名}")注解来加载对应的配置属性,具体如下:

 @Value("${com.dongk.selfproperty.title}")
 private String title;
 @Value("${com.dongk.selfproperty.name}")
 private String name;

参数间的引用

com.dongk.selfproperty.title=wangdk
com.dongk.selfproperty.name=哈哈
com.dongk.selfproperty.union=${com.dongk.selfproperty.title}合并 ${com.dongk.selfproperty.name}

使用随机数

在一些情况下,有些参数我们需要希望它不是一个固定的值,比如密钥、服务端口等。Spring Boot的属性配置文件中可以通过${random}来产生int值、long值或者string字符串,来支持属性的随机值。

# 随机字符串
com.dongk.selfproperty.value=${random.value}
# 随机int
com.dongk.selfproperty.number=${random.int}
# 随机long
com.dongk.selfproperty.bignumber=${random.long}
# 10以内的随机数
com.dongk.selfproperty.test1=${random.int(10)}
# 10-20的随机数
com.dongk.selfproperty.test2=${random.int[10,20]}

多环境配置

我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。

对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包,Spring Boot也不例外,或者说更加简单。

在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:

  • application-dev.properties:开发环境
  • application-test.properties:测试环境
  • application-prod.properties:生产环境

至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

如:spring.profiles.active=test就会加载application-test.properties配置文件内容

原文地址:https://www.cnblogs.com/mongo/p/8358953.html