配置文件详解:properties和yaml_凌枫zero的博客-爱代码爱编程
一.配置文件的生效顺序,会对值进行覆盖:
1. @TestPropertySource 注解
2. 命令行参数
3. Java系统属性(System.getProperties())
4. 操作系统环境变量
5. 只有在random.*里包含的属性会产生一个RandomValuePropertySource
在properties文件中设置随机值,随机数等
#这个优先级较低
#32位随机字符串
roncoo.secret=${random.value}
#int类型的随机数字
roncoo.number=${random.int}
roncoo.name=www.roncoo.com
#属性占位符属性
roncoo.desc=${roncoo.name} is a domain name
#应用端口
server.port=8090
#时间格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#时区设置
spring.jackson.time-zone=Asia/Chongqing
在IndexController层中获取
package com.roncoo.education.controller;
import java.util.Date;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.roncoo.education.bean.User;
/**
* spring-boot-demo-3-1
*
* @author wujing
*/
@RestController
@RequestMapping(value = "/index")
public class IndexController {
@Value(value = "${roncoo.secret}")
private String secret;
@Value(value = "${roncoo.number}")
private int id;
@Value(value = "${roncoo.desc}")
private String desc;
@RequestMapping
public String index() {
return "hello world";
}
// @RequestParam 简单类型的绑定,可以出来get和post
@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
map.put("secret", secret);
map.put("id", id);
map.put("desc", desc);
return map;
}
// @PathVariable 获得请求url中的动态参数
@RequestMapping(value = "/get/{id}/{name}")
public User getUser(@PathVariable int id, @PathVariable String name) {
User user = new User();
user.setId(id);
user.setName(name);
user.setDate(new Date());
return user;
}
}
二.配置随机值
roncoo.secret=${random.value}
roncoo.number=${random.int}
roncoo.bignumber=${random.long}
roncoo.number.less.than.ten=${random.int(10)}
roncoo.number.in.range=${random.int[1024,65536]}
读取使用注解:@Value(value = "${roncoo.secret}")
注:出现黄点提示,是要提示配置元数据,可以不配置
6. 在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量)
7. 在打包的jar内的应用程序配置文件(application.properties,包含YAML和profile变量)
8. 在@Configuration类上的@PropertySource注解
9. 默认属性(使用SpringApplication.setDefaultProperties指定)
三.属性占位符
当application.properties里的值被使用时,它们会被存在的Environment过滤,所以你能够引用先前定义的值(比如,系统属性)。
roncoo.name=www.roncoo.com
roncoo.desc=${roncoo.name} is a domain name
四.Application属性文件,按优先级排序,位置高的将覆盖位置低的
1. 当前目录下的一个/config子目录
2. 当前目录
3. 一个classpath下的/config包
4. classpath根路径(root)
这个列表是按优先级排序的(列表中位置高的将覆盖位置低的)
五. 配置应用端口和其他配置的介绍
#端口配置:
server.port=8090
#时间格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#时区设置
spring.jackson.time-zone=Asia/Chongqing
六. 使用YAML代替Properties
注意写法:冒号后要加个空格