Spring Boot配置文件支持properties和YAML格式,YAML因可读性强更受欢迎;配置文件默认放在src/main/resources目录下,支持多环境配置如application-dev.yml;加载优先级从高到低为命令行参数、环境变量、外部配置文件、内部配置文件等;YAML可通过缩进配置List和Map,结合@ConfigurationProperties绑定对象;可通过spring.profiles.active激活指定环境,也可使用@PropertySource或SpringApplicationBuilder加载额外配置。

Spring Boot 配置文件主要有 properties 和 YAML 两种类型。Properties 格式简单,但可读性稍差;YAML 格式更具层次感,可读性更好,配置也更灵活。选择哪种取决于个人偏好和项目需求,不过现在 YAML 越来越流行了。
Properties 和 YAML 都是用来配置 Spring Boot 应用的,区别在于它们的语法和表达能力。
Spring Boot 配置文件应该放在哪里?
Spring Boot 默认会从以下位置加载配置文件:
/config 子目录/config 包所以,通常我们把 application.properties 或 application.yml 放在 src/main/resources 目录下,Spring Boot 启动时会自动加载。如果需要更灵活的配置,比如区分不同环境,可以使用 application-{profile}.properties 或 application-{profile}.yml,并设置 spring.profiles.active 属性来激活对应的 profile。
Properties 和 YAML 配置文件的优先级是怎样的?
如果同时存在多种配置文件,Spring Boot 会按照一定的优先级加载它们。优先级从高到低依次是:
SPRING_APPLICATION_JSON 的属性 (嵌入在环境变量或系统属性中的 JSON)java:comp/env 的 JNDI 属性System.getProperties())random.* 配置的 RandomValuePropertySource
SpringApplication.setDefaultProperties 指定的默认属性简单来说,命令行参数的优先级最高,jar 包内部的默认配置文件优先级最低。
YAML 配置文件如何配置 List 和 Map?
YAML 配置文件在处理 List 和 Map 方面非常方便,可读性也很好。
List 的配置:
my:
list:
- item1
- item2
- item3对应的 Java 代码:
@ConfigurationProperties(prefix = "my")
public class MyConfig {
private List<String> list;
// getter and setter
}Map 的配置:
my:
map:
key1: value1
key2: value2
key3: value3对应的 Java 代码:
@ConfigurationProperties(prefix = "my")
public class MyConfig {
private Map<String, String> map;
// getter and setter
}YAML 语法简洁,使用缩进表示层级关系,非常适合配置复杂的对象。
如何在 Spring Boot 中使用多个配置文件?
有时候,我们需要根据不同的环境或功能模块使用多个配置文件。Spring Boot 提供了几种方式来实现:
Profile-specific 配置文件:
这是最常用的方式,通过 application-{profile}.properties 或 application-{profile}.yml 来区分不同环境的配置。例如,application-dev.properties 用于开发环境,application-prod.properties 用于生产环境。通过设置 spring.profiles.active 属性来激活对应的 profile。
使用 @PropertySource 注解:
可以在配置类中使用 @PropertySource 注解来加载额外的配置文件。例如:
@Configuration
@PropertySource("classpath:my-config.properties")
public class MyConfig {
// ...
}使用 SpringApplicationBuilder:
可以通过 SpringApplicationBuilder 来指定额外的配置文件。例如:
public static void main(String[] args) {
new SpringApplicationBuilder(MyApplication.class)
.properties("spring.config.name=my-config")
.run(args);
}这种方式可以指定配置文件的名称,Spring Boot 会自动加载 my-config.properties 或 my-config.yml。
选择哪种方式取决于具体的需求。Profile-specific 配置文件适用于不同环境的配置,@PropertySource 适用于加载特定的配置文件,SpringApplicationBuilder 适用于更灵活的配置方式。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号