02.7Spring Boot 3配置文件管理

分类: Spring 6和Spring Boot 3基础

Spring Boot 3 配置文件管理

Spring Boot 支持多种配置文件格式,并提供了强大的配置管理功能。合理管理配置文件,是构建可维护应用的关键。

本节将学习:application.properties vs application.yml、多环境配置(dev、test、prod)、@ConfigurationProperties,以及配置加密。

application.properties vs application.yml

格式对比

application.properties:

server.port=8080 spring.application.name=demo spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password

application.yml:

server: port: 8080 spring: application: name: demo datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: password

选择建议

推荐使用 YAML:

  • ✅ 层次清晰
  • ✅ 支持多环境配置
  • ✅ 更易读

多环境配置(dev、test、prod)

配置文件结构

src/main/resources/
├── application.yml          # 主配置
├── application-dev.yml      # 开发环境
├── application-test.yml     # 测试环境
└── application-prod.yml     # 生产环境

配置示例

application.yml(主配置):

spring: profiles: active: dev # 默认使用开发环境

application-dev.yml:

server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/mydb_dev username: root password: dev_password logging: level: root: DEBUG

application-prod.yml:

server: port: 8080 spring: datasource: url: jdbc:mysql://prod-server:3306/mydb_prod username: ${DB_USERNAME} password: ${DB_PASSWORD} logging: level: root: INFO

激活环境

方式1:配置文件

spring: profiles: active: prod

方式2:命令行

java -jar app.jar --spring.profiles.active=prod

方式3:环境变量

export SPRING_PROFILES_ACTIVE=prod

@ConfigurationProperties

类型安全的配置

@ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private int port; private Database database; // getters and setters public static class Database { private String url; private String username; private String password; // getters and setters } }

启用配置属性

@SpringBootApplication @EnableConfigurationProperties(AppProperties.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

使用配置属性

@Service public class MyService { private final AppProperties properties; public MyService(AppProperties properties) { this.properties = properties; } public void doSomething() { System.out.println("App name: " + properties.getName()); System.out.println("Database URL: " + properties.getDatabase().getUrl()); } }

配置加密

敏感信息加密

使用 Jasypt 加密

1. 添加依赖:

<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.5</version> </dependency>

2. 加密配置:

spring: datasource: password: ENC(encrypted_password)

3. 设置密钥:

export JASYPT_ENCRYPTOR_PASSWORD=mySecretKey

官方资源

本节小结

在本节中,我们学习了:

第一个是配置文件格式。 application.properties 和 application.yml 的区别,推荐使用 YAML。

第二个是多环境配置。 通过 Profile 管理不同环境的配置。

第三个是 @ConfigurationProperties。 类型安全的配置属性,更好的 IDE 支持。

第四个是配置加密。 使用 Jasypt 或其他工具加密敏感信息。

这就是 Spring Boot 3 配置文件管理。合理管理配置,是构建可维护应用的关键。

在下一节,我们将创建第一个 Spring Boot 3 应用,实践所学知识。