两种配置文件的格式
在springboot框架中,resource文件夹里可以存放配置的文件有两种:properties和yml。
1、application.properties的用法:扁平的k/v格式。
server.port=8801
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http\://localhost\:${server.port}/eureka/
2、application.yml的用法:树型结构。
server:
port: 8801
eureka:
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://localhost:8801/eureka/
两种前者是,而后者是yml的,建议使用后者,因为它的可读性更强,如果现有是properties,也可以转换成yml格式,我们把properies里按.去拆分即可。
两种配置文件的读取
例application.properties:
test.name=guoqing
test.birth=1001
test.mj=980
application.yml:
test:
mj: 960
使用@Value注解读取
1\
@Value("${demo.name}")
private String name;
@Value("${demo.age}")
private String age;
@Value("${test.mj}")
private String mj;
@RequestMapping("/getProperties")
public String getProperties(){
log.info("读取properties文件结果:name->{};birth->{};mj->{}",name,birth,mj);
return "读取properties文件结果name->"+name+";birth->"+birth;
}
运行结果:
2\
也可以单独放在一个类
@Component
public class China {
@Value("${test.name}")
private String name;
@Value("${test.birth}")
private String birth;
@Value("${test.mj}")
private String mj;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getMj() {
return mj;
}
public void setMj(String mj) {
this.mj = mj;
}
}
调用
public class TestController {
@Autowired
private China china;
@RequestMapping("/getProperties")
public String getProperties(){
log.info("读取结果:name->{};birth->{};mj->{}",
china.getName(),china.getBirth(),china.getMj());
return "读取properties文件结果name->"+china.getName()+";birth->"+china.getBirth();
}
}
两种配置文件的优先级
优先读取properties文件,如果properties文件中没有再去读yml文件。
- application.properties(或者application.yml)中包含系统属性、环境变量、命令参数这类信息。
- application.yml代码量 更少,层次更加分明,结构更加清晰,推荐使用application.yml