在 Spring Boot 开发中,配置文件是应用运行的核心。无论是开发、测试还是生产环境,配置文件都起到了至关重要的作用。Spring Boot 提供了两种主流的配置文件格式:Properties 和 YAML。它们各有特点,适用于不同的场景。
本文将从以下几个方面详细解析 Spring Boot 的配置文件:
@Value
和 @ConfigurationProperties
注解通过本文的学习,你将能够全面掌握 Spring Boot 的配置文件管理技巧,并在实际开发中灵活运用。
Properties 文件 是 Java 世界中最常见的配置文件格式,以其简单易用的特点广受欢迎。
=
分隔。\
表示续行。示例:
# application.properties
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
YAML 文件 是一种更为现代化的配置文件格式,因其简洁和强大的表达能力而备受青睐。
.yaml
或 .yml
。示例:
# application.yaml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
特性 | Properties | YAML |
---|---|---|
文件扩展名 | .properties |
.yaml 或 .yml |
语法风格 | 键值对,无层级结构 | 使用缩进表示层级结构 |
适用场景 | 简单的键值对配置 | 复杂的嵌套配置 |
是否支持多行 | 支持(使用 \ 续行) |
支持(自然换行) |
是否支持复杂结构 | 不支持 | 支持(列表、映射等) |
在实际开发中,应用通常需要在多个环境中运行(如开发环境、测试环境、生产环境)。Spring Boot 提供了灵活的多环境配置解决方案。
Spring Boot 支持通过在配置文件名后添加 -profile
后缀来区分不同环境。例如:
application.properties
:默认配置文件。application-dev.properties
:开发环境配置。application-test.properties
:测试环境配置。application-prod.properties
:生产环境配置。要激活某个 Profile,可以通过以下几种方式:
通过命令行参数:
java -jar myapp.jar --spring.profiles.active=dev
2 .通过系统环境变量:
export SPRING_PROFILES_ACTIVE=dev
3.通过 application.properties
文件
spring.profiles.active=dev
@Value
和 @ConfigurationProperties
除了使用 Spring Boot 提供的默认配置外,我们还可以根据需求定义自己的配置项。
@Value
注解@Value
是 Spring 提供的一个注解,用于从配置文件中读取值并注入到组件中。
示例:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyConfig {
@Value("${my.custom.property}")
private String customProperty;
// Getter and Setter methods
}
在 application.properties
中定义:
my.custom.property=Hello, World!
@ConfigurationProperties
注解@ConfigurationProperties
是 Spring Boot 提供的一个更强大的注解,适用于管理复杂的自定义配置。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "my.custom")
public class MyConfig {
private String property1;
private Integer property2;
// Getters and Setters
}
在 application.properties
中定义:
my.custom.property1=Value1
my.custom.property2=123
Spring Boot 在加载配置文件时遵循一定的优先级规则。以下是默认的加载顺序:
application.properties
和 application.yaml
文件。application-dev.properties
)。