文章目录
虽然 Spring Boot 的自动化配置帮我们完成了很多工作,但在实际运用时,我们有时需要自定义配置环境,此时就需掌握配置文件的使用
Spring Boot 的配置文件有以下两种形式:
- Properties
- Yaml
一、配置文件的位置
要掌握配置文件的使用,首先必须要明确 Spring Boot 配置文件出现的位置
不管是 properties 还是 yaml 格式,Spring Boot 的配置文件可出现在如下 4 个地方:
- 项目根目录下的 config 目录下
- src / main / java / resources / config 下
- src / main / java / resources 下
- 项目根目录下
当同时出现多个配置文件时,会有一个优先级
配置文件优先级排序:1 > 4 > 2 > 3
二、配置文件的基本语法
1、Properties
- key = value 的键值对形式
server.port=8081
2、Yaml
- key: value 的键值对形式,对空格与缩进有严格要求!
server:
port: 8080
- yaml 需要在属性(键值)的后面加 1 个空格!上方的冒号后面必须要有 1 个空格才能被解析!
- yaml 对缩进有严格要求,缩进表示下一级,如对象的属性相对对象名要缩进一层
可以看到,yaml 方式更为简洁方便,官方也是推荐使用 yaml 格式的配置文件
三、对象属性注入
1、Yaml 写法
现有一个 User 实体类,其具有以下类型的属性:String, Integer, boolean, Date, Map, List, Group(内嵌对象)
我们可以在配置文件中定义好属性值,然后通过 Spring Boot 提供的 @ConfigurationProperties
注解将属性值注入到实体类中
同时还要添加 @Component
注解,将其注册为一个组件,交由 Spring 容器进行管理
User
@Component
@ConfigurationProperties(prefix = "myuser")
public class User {
private String name;
private Integer age;
private boolean isActive;
private Date registerTime;
private Map<String,Object> map;
private List<Object> list;
private Group group;
appliaction.yaml
myuser:
name: good
age: 100
isActive: false
registerTime: 2021/01/01
map: {a: 1,b: 2}
list:
- 1
- good
- true
group:
name: zuiniu
count: 666
application.yaml 中的对象名与属性名要和实体类一致,否则会出现属性值为 Null 的情况
Test
@SpringBootTest
class Springboot02ConfigApplicationTests {
@Autowired
private User user;
@Test
void contextLoads() {
System.out.println(user);
}
}
在测试类中,通过 @Autowired
注解获得 Spring 容器中的 user 对象,输出对象的属性值如下所示:
2、Properties 写法
application.properties
name= good
age= 100
isActive= false
registerTime= 2021/01/01
在实体类中使用 @PropertySource
注解读入配置文件 application.properties
然后使用 @Value
注解注入属性值
User
@Component
@PropertySource(value = "classpath:application.properties")
public class User {
@Value("${name}")
private String name;
@Value("${age}")
再次运行,结果如下:
可以看到,name 与 age 注入成功,其他没有写的属性则为 null
四、多环境配置与切换
在实际运用时,程序可能有多种环境,如开发版、测试版等,此时需要有多个配置文件,因而就会对配置文件进行一个选择
1、Properties
假设此时有以下 3 个配置文件:
application-dev.properties
server.port=8081
application-test.properties
server.port=8082
对于以上 2 个配置文件,我们可在主配置文件中进行选择激活
application.propertis
spring.profiles.active=test
通过 spring.profiles.active
指定激活的配置文件,test 代表 application-test.properties
程序最终选择的 tomcat 端口为 test 中的 8082,运行结果如下:
2、Yaml
yaml 中用三条杠来划分不同的配置文件,spring:profiles
指定配置文件名,active
进行配置文件的选择,更为简洁方便
application.yaml
server:
port: 8080
spring:
profiles:
active: test
---
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: test
程序最终选择的 tomcat 端口为 test 中的 8082,运行结果如下:
五、小结
对比 Properties 与 Yaml,我们不难看出 Yaml 的形式更为简洁直观、功能更为强大,如在复杂对象属性的书写注入与多环境的配置切换方面,所以推荐使用 Yaml 作为 Spring Boot 程序的配置文件!