
Spring Boot配置文件支持占位符,一些用法如下:
为server.port设置一个随机端口
server:port: ${random.int}
// 随机数占位符${random.value} - 类似uuid的随机数,没有"-"连接${random.int} - 随机取整型范围内的一个值${random.long} - 随机取长整型范围内的一个值${random.long(100,200)} - 随机生成长整型100-200范围内的一个值${random.uuid} - 生成一个uuid,有短杠连接${random.int(10)} - 随机生成一个10以内的数${random.int(100,200)} - 随机生成一个100-200 范围以内的数
server: port: ${APP_PORT:8080}app: name: My Application timestamp: #{T(java.time.LocalDateTime).now()}spring: profiles: active: dev application: name: ${APP_NAME:app-name} jackson: serialization: #格式化输出 indent_output: true
有时某个配置项可能没有被配置,或者配置项的值为空。为了避免空指针异常,我们可以为占位符提供一个默认值。默认值可以在占位符后面使用冒号和默认值的形式进行指定
默认值
占位符获取之前配置的值,如果没有可以使用“冒号”指定默认值格式.
例如,server.port是属性层级及名称,如果该属性不存在,冒号后面填写默认值
${server.port:8080}
如果server.port值为不存在,就会取8080,如果存在,则取server.port的值。
spring: jackson: #日期格式化 date-format: yyyy-MM-dd HH:mm:ss serialization: #格式化输出 indent_output: true #忽略无法转换的对象 fail_on_empty_beans: false #设置空如何序列化 defaultPropertyInclusion: NON_EMPTY deserialization: #允许对象忽略json中不存在的属性 fail_on_unknown_properties: false parser: #允许出现特殊字符和转义符 allow_unquoted_control_chars: true #允许出现单引号 allow_single_quotes: true #兼容反斜杠,允许接受引号引起来的所有字符 allow_backslash_escaping_any_character: true
spring.jackson.serialization.indent-output=true配置项的作用
生成的 JSON 字符串会按照固定的格式进行缩进,使得 JSON 字符串更加易读
- ObjectMapper mapper = new ObjectMapper();
- mapper.enable(SerializationFeature.INDENT_OUTPUT);
- TestObject obj = new TestObject();
- String json = mapper.writeValueAsString(obj);
生成的 JSON 字符串
{ "field1": "value1", "field2": 123, "field3": { "subfield1": "subvalue1", "subfield2": "subvalue2" }}
当关闭 spring.jackson.serialization.indent-output 时,生成的 JSON 字符串会采用紧凑格式,所有的元素都放在一行上,不进行缩进。
如下所示:
{"field1":"value1","field2":123,"field3":{"subfield1":"subvalue1","subfield2":"subvalue2"}}