2.配置文件详解:Properties和YAML
一.配置文件的生效顺序,会对值进行覆盖:
@TestPropertySource 注解
命令行参数
Java系统属性(System.getProperties())
操作系统环境变量
只有在random.*里包含的属性会产生一个RandomValuePropertySource
在打包的jar外的应用程序配置文件(application.properties,包含YAML和profile变量)
在打包的jar内的应用程序配置文件(application.properties,包含YAML和profile变量)
在@Configuration类上的@PropertySource注解
默认属性(使用SpringApplication.setDefaultProperties指定)
1配置最优先,9最低
二.配置随机值
src/main/resources/application.properties文件中加入配置
demo.secret=${random.value}
demo.number=${random.int}
demo.bignumber=${random.long}
demo.number.less.than.ten=${random.int(10)}
demo.number.in.range=${random.int[1024,65536]}
注:出现黄点提示,是要提示配置元数据,可以不配置 demo可以为任意自定义字符
读取使用注解:@Value(value = "${demo.secret}")
,这样就可以在项目中采用注释调用了
在类中加入成员变量,则就可以在类中使用成员变量secret,number了
@Value(value = "${demo.secret}")
private String secret;
@Value(value = "${demo.number}")
private String number;
加入类方法
@RequestMapping(value = "getRandom")
public Map<String, Object> get() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("secret", secret);
map.put("number", number);
return map;
}
访问:http://localhost:8080/getRandom

三.属性占位符
当application.properties里的值被使用时,它们会被存在的Environment过滤,所以你能够引用先前定义的值(比如,系统属性)。
src/main/resources/application.properties文件中加入配置
demo.name=www.shujuwajue.com
demo.desc=${demo.name} is a domain name
在类中加入成员变量,则就可以在类中使用成员变量name,desc了
@Value(value = "${demo.name}")
private String name;
@Value(value = "${demo.desc}")
private String desc;
加入类方法
@RequestMapping(value = "info")
public Map<String, Object> info() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("desc", desc);
return map;
}

四.Application属性文件,按优先级排序,位置高的将覆盖位置低的
当前目录下的一个/config子目录
当前目录
一个classpath下的/config包
classpath根路径(root)
这个列表是按优先级排序的(列表中位置高的将覆盖位置低的,,也就是1配置最优先,4最低)
classpath的理解可以参考:spring boot加载资源路径配置和classpath问题解决
校验一下3和4:
resource目录下创建config目录,并创建application.properties文件
加入demo.desc=${demo.name} is anewdomain name

访问测试:http://localhost:8080/info

五. 配置应用端口和其他配置的介绍
#端口配置:application.properties
server.port=8090
#时间格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#时区设置
spring.jackson.time-zone=Asia/Chongqing
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss 格式化new Date()的格式
同样也可以在src/main/resources/application.properties文件中加入配置,也可以根据配置文件的优先级加入相应的配置文件中。
六. 使用YAML代替Properties
src/main/resources/下的 application.properties 重命名为 application.yaml
#自定义配置
demo:
secret: ${random.value}
number: ${random.int}
name: www.shujuwajue.com
desc: ${demo.name} is a domain name
#端口
server:
port: 8090
#spring jsckson
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Chongqing
注意写法:冒号后要加个空格
资料
server.context-path=/admin //配置访问上下文,访问时候需要localhost/admin/xxxx
Last updated
Was this helpful?