您的位置:首页 > 编程语言 > Java开发

Spring Boot项目属性配置

2017-08-02 13:53 483 查看
一、Spring Boot的属性配置文件包括两种,一种为默认的properties,另一种为yml的,yml相比于properties更为简洁,所以推荐使用yml的配置文件。

properties的配置文件
#properties的配置文
server.port=8081
server.context-path=/gril

yml的配置文件
server:
port: 8080
context-path: /gril

以上两种配置方式作用相同,效果一致,使用时选择其中一种即可。

二、引用yml中的属性

yml文件
server:
port: 8080
cupSize: B


java
/**
* 通过注解将配置文件cupSize里的内容注入到cupSize属性
*/
@Value("${cupSize}")
private String cupSize;
//运行打印结果
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String say() {
return cupSize;
}

        注意:配置文件里的属性和server同级才可这样引用,否则无法启动项目

三、这么写配置有点累,有一个属性要写一个,有10个或更多呢?有没有一种办法让我们只写一次就可以呢?当然有。那么如何把配置写到一个类里面去?代码如下。

yml
server:
port: 8080
gril:
cupSize: B
age: 18
context: "cupSize:${cupSize},age:${age}"


GrilProperties
/**
* ConfigurationProperties注解获取前缀是gril的配置
*/
@Component
@ConfigurationProperties(prefix = "gril")
public class GrilProperties {
private String cupSize;

private Integer age;

public String getCupSize() {
return cupSize;
}

public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}


引用配置HelloController
@RestController
public class HelloController {
@Autowired
private GrilProperties grilProperties;
//运行打印结果
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String say() {
return grilProperties.getCupSize();
}
}


四、多环境配置:在开发环境和生产环境需要使用不同的配置,但不可能一直改配置,这是怎么办呢?开发环境一个配置文件生产环境一个配置文件,然后用总的配置文件引用

开发环境
#  开发环境
server: port: 8080 gril: cupSize: B age: 18 context: "cupSize:${cupSize},age:${age}"


生产环境
#  生产环境
server:
port: 8081
gril:
cupSize: F
age: 18
context: "cupSize:${cupSize},age:${age}"


总的配置
spring:
profiles:
# active: prod 生产环境
# active: dev 开发环境
active: prod
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Spring Boot