学习 Spring Boot 项目中的配置文件( yaml 格式),如: application.yaml 。
Spring Boot 项目中的配置文件 application.yaml
最常见的位置在 src/main/resources
目录下,其实共有 4 个默认位置能放,如下(优先级: 1 > 2 > 3 > 4 ):
Spring Boot 启动时,默认会从这 4 个位置按顺序去查找相关属性并加载,重复的属性以优先级高的为准。
但并非绝对的,我们也可以自定义位置(如:src/main/resources/cxy35/application.yaml
),并在项目启动时通过 spring.config.location
属性来手动的指定配置文件的位置,指定方式如下:
java -jar spring-boot-yaml-0.0.1-SNAPSHOT.jar --spring.config.location=classpath:/cxy35/
注意:通过 spring.config.location
属性指定时,表示自己重新定义配置文件的位置,项目启动时就按照定义的位置去查找配置文件,这种定义方式会覆盖掉默认的 4 个位置。另外可以通过 spring.config.additional-location
属性来指定,表示在默认的 4 个位置的基础上,再添加几个位置,新添加的位置的优先级大于原本的位置。
Spring Boot 项目中的配置文件默认文件名是 application.yaml
,与文件位置类似,也可以自定义,比如叫 app.yaml
,并在项目启动时通过 spring.config.name
属性来手动的指定配置文件的文件名,如:java -jar spring-boot-yaml-0.0.1-SNAPSHOT.jar --spring.config.name=app
。
当然,配置文件的位置和文件名可以同时自定义。
首先在 application.yaml
配置文件中定义属性:
book:
id: 1
name: 三国演义
author: 罗贯中
editors:
- 张三
- 李四
chapters:
- id: 1
name: 第一章 桃园结义
- id: 2
name: 第二章 除董卓
再定义一个 Book 和 Chapter 类,并通过 @Value
注解将这些属性注入到 Book 对象中(注意: Book 对象必须要交给 Spring 容器去管理):
@Component
public class Book {
@Value("${book.id}")
private Long id;
@Value("${book.name}")
private String name;
@Value("${book.author}")
private String author;
@Value("${book.editors}")
private List<String> editors; // 普通数组/列表注入
@Value("${book.chapters}")
private List<Chapter> chapters; // 对象数组/列表注入
// getter/setter
}
public class Chapter {
private Long id;
private String name;
// getter/setter
}
因为 application.yaml
配置文件会被自动加载,所以上述属性可以注入成功,可通过在 controller 或者单元测试中注入 Book 对象来测试。
yaml 配置目前不支持 @PropertySource
注解。
上述方式在 Spring 中也可以使用,和 Spring Boot 没有关系。
当配置的属性非常多的时候,上述方式工作量大且容易出错,所以就不合适了。在 Spring Boot 中引入了类型安全的属性注入,通过 @ConfigurationProperties
注解来实现,如下:
@Component
@ConfigurationProperties(prefix = "book")
public class Book {
private Long id;
private String name;
private String author;
private List<String> editors; // 普通数组/列表注入
private List<Chapter> chapters; // 对象数组/列表注入
// getter/setter
}
@PropertySource
注解。扫码关注微信公众号 程序员35 ,获取最新技术干货,畅聊 #程序员的35,35的程序员# 。独立站点:https://cxy35.com