许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。
yml跟properties 例如设置端口为:8000 application.properties
server.port=8000
server.context-path=/shuibo
application.yml
server:
port: 8000
context-path: /shuibo #使用localhost:8000/shuibo
yaml是JSON的一个超集,是一种结构层次清晰明了的数据格式,简单易读易用, Spring Boot对SnakeYAML库做了集成,所以可以在Spring Boot项目直接使用。
Spring Boot配置优先级顺序,从高到低:
一般在实际项目中会有多个环境,比如: 测试环境 -> 正式环境 -> …
每个环境的配置比如:Sql链接,redis配置之类都不一样,通过配置文件决定启用的配置文件。
spring:
profiles:
active: pro
1.在application.yml配置key value 例如:
获取配置
浏览器输入:localhost:8000/index
2.通过ConfigBean 添加配置
创建ConfigBean
@Component
@ConfigurationProperties(prefix = "bobby")//获取前缀为bobby下的配置信息
public class ConfigBean {
private String name;//名字与配置文件中一致
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
获取配置
@RestController
public class IndexController {
@Autowired
private ConfigBean configBean;
@RequestMapping("/config")
public String config(){
return "姓名:" + configBean.getName() + ",年龄:" + configBean.getAge();
}
}
本文讲述了配置文件的加载顺序,properties跟yml区别,通过两种方式读取配置文件。
本文GitHub地址:https://github.com/ishuibo/SpringAll