1. 获取 application.yml
文件中的数据:
- 方式一:
- 假设我在
application.yml
文件中有一个配置为:
# 自定义的配置
cupSize: B
age: 18
content: "cupSize:${cupSize}, age:${age}"
- 那么可以通过
@Value
取出其中的值
package com.mm.service_learn_whole_project.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${cupSize}")
private String cupSize;
@Value("${age}")
private Integer age;
@Value("${content}")
private String content;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "cpuSize is " + cupSize+" and age is "+age+"</br>and content is "+content;
}
}
-
打印结果
- 方式二:
- 假设我在
application.yml
中的配置为:
# 自定义的配置
girl:
cupSize: B
age: 18
- 创建一个 Properties 类;
package com.mm.service_learn_whole_project.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String cupSize;
private Integer age;
// 省略了 getter / setter 方法
}
- 使用:
package com.mm.service_learn_whole_project.controller;
import com.mm.service_learn_whole_project.config.GirlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "cpuSize is " + girlProperties.getCupSize()+" and age is "+girlProperties.getAge();
}
}
-
打印结果
2. 快速更改配置内容
- 在
resource
文件夹下创建三个yml
文,分别取名为application.yml
application-dev.yml
(开发环境)application-pro.yml
(生产环境);
- 在 开发环境 和 生产环境 中添加不同配置;
- 然后在
application.yml
文件中添加以下配置,即可根据需求切换配置文件;
spring:
profiles:
active: dev #开发环境
# active: pro #生产环境