Spring Boot 配置文件深度解析

Spring Boot 配置文件深度解析(2026 最新版)

Spring Boot 的配置文件是整个应用的核心“控制中心”,它决定了应用的端口、数据库连接、日志级别、自定义属性等几乎所有行为。Spring Boot 提供了强大而灵活的配置机制,支持多种格式、多环境切换、优先级层级、外部化配置等。本文从基础到高级,全面深度解析 Spring Boot 配置文件。

1. 支持的配置文件格式与命名

Spring Boot 默认支持两种主流格式(优先级:properties > yaml):

文件名格式说明推荐场景
application.propertiesProperties键值对格式,简单直观小项目、快速原型
application.yml / application.yamlYAML层级结构更清晰,支持列表、对象中大型项目(强烈推荐)

同时存在时的优先级application.properties > application.yml(同名属性以 properties 为准)

2. 多环境配置文件(Profile)

Spring Boot 支持根据不同环境加载不同配置,非常适合开发、测试、生产分离。

命名规则

  • application-dev.yml(开发环境)
  • application-prod.yml(生产环境)
  • application-test.yml(测试环境)

激活方式(任选其一):

  1. application.yml 中设置:
   spring:
     profiles:
       active: dev
  1. 启动参数:
   java -jar app.jar --spring.profiles.active=prod
  1. IDEA 配置:Run → Edit Configurations → Active profiles 填 prod
  2. 环境变量:SPRING_PROFILES_ACTIVE=prod

优先级:特定 profile 配置会覆盖主配置文件 application.yml 中的同名属性。

示例

# application.yml(通用配置)
server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testdb

# application-prod.yml(生产覆盖)
server:
  port: 80
spring:
  datasource:
    url: jdbc:mysql://prod-server:3306/proddb
    username: prod_user

3. 配置属性优先级(从高到低,2026 最新版共 23 级)

Spring Boot 配置来源非常多,优先级如下(越高越优先,覆盖低优先级同名属性):

  1. 命令行参数(--server.port=9090
  2. SPRING_APPLICATION_JSON 环境变量
  3. Java System Properties(System.getProperties()
  4. 操作系统环境变量
  5. application-{profile}.properties/yml(jar 外部)
  6. application.properties/yml(jar 外部)
  7. 项目内 application-{profile}.properties/yml
  8. 项目内 application.properties/yml
  9. @PropertySource 注解加载的配置
  10. 默认属性(@SpringBootApplication 中的 defaultProperties

实战建议

  • 生产环境用命令行或环境变量覆盖敏感配置(如密码)
  • 开发时用 application-dev.yml 放本地配置

4. YAML 配置文件高级语法(比 properties 强大得多)

YAML 支持复杂数据结构,非常适合配置对象、列表、多环境。

基本语法示例

# 普通键值
server:
  port: 8080
  servlet:
    context-path: /api

# 对象嵌套
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

# 列表
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus

# 数组写法
books:
  - title: Java编程思想
    price: 99.0
  - title: Spring Boot实战
    price: 89.0

# 多环境配置(推荐写法)
---
spring:
  profiles: dev
server:
  port: 8081
---
spring:
  profiles: prod
server:
  port: 80

简化写法(推荐):

spring:
  datasource:
    hikari:
      maximum-pool-size: 20
      connection-timeout: 30000

5. 自定义配置属性与 @ConfigurationProperties

Spring Boot 允许将配置绑定到 Java 对象上,实现类型安全配置。

步骤

  1. 添加依赖(通常已包含):
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-configuration-processor</artifactId>
       <optional>true</optional>
   </dependency>
  1. 创建配置类:
@Component
@ConfigurationProperties(prefix = "app")  // 前缀 app
@Data
public class AppProperties {
    private String name;
    private String version;
    private List<String> admins;
    private Database database;

    @Data
    public static class Database {
        private String host;
        private int port;
        private String username;
    }
}
  1. application.yml 中配置:
app:
  name: 图书购买系统
  version: 1.0.0
  admins:
    - admin1@example.com
    - admin2@example.com
  database:
    host: localhost
    port: 3306
    username: root
  1. 使用:
@Autowired
private AppProperties appProperties;

public void printConfig() {
    System.out.println(appProperties.getName());
    System.out.println(appProperties.getDatabase().getHost());
}

优点

  • 类型安全(IDE 提示、编译检查)
  • 支持复杂对象、列表、嵌套
  • 支持校验(配合 @Validated + Bean Validation)

6. 随机值与占位符

app:
  secret: ${random.uuid}                  # 生成随机 UUID
  number: ${random.int(1000,9999)}        # 随机端口或验证码
  token-length: ${random.int[10,20]}      # 范围随机

# 占位符引用
server:
  port: ${SERVER_PORT:8080}               # 环境变量不存在时用默认值

7. 外部化配置最佳实践(生产必备)

场景推荐方式
数据库密码环境变量或命令行参数
多环境切换Profile + 外部 config 目录
云部署(K8s/Docker)ConfigMap + 环境变量
敏感信息从不写在代码仓库,用外部配置覆盖

外部配置目录
运行时指定:

java -jar app.jar --spring.config.location=/etc/config/application-prod.yml

8. 总结:配置优先级记忆口诀

命外内默”:

  • 令行参数最高
  • 部配置文件(jar 外)
  • 部配置文件(jar 内)
  • 认属性最低

掌握了 Spring Boot 的配置文件机制,你就能轻松管理复杂应用的配置,实现开发、测试、生产环境的完美隔离!

如果想看具体案例(如整合 MySQL、Redis 的完整配置),或者外部化配置的 Docker/K8s 实践,随时告诉我,我继续深度讲解!🚀

文章已创建 3707

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部