Skip to content
清晨的一缕阳光
返回

Spring Boot 配置管理详解

前言

配置管理是企业应用开发中的重要环节。Spring Boot 提供了强大的配置管理能力,支持多环境配置、外部化配置、配置加密等功能。本文将详细介绍 Spring Boot 配置管理的最佳实践。

配置文件格式

application.properties

传统的 properties 格式:

# 服务器配置
server.port=8080
server.servlet.context-path=/api

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Redis 配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0

application.yml

推荐的 YAML 格式,更简洁:

server:
  port: 8080
  servlet:
    context-path: /api

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  redis:
    host: localhost
    port: 6379
    password: 
    database: 0

application.yaml vs application.yml

两者完全等价,yml 是 yaml 的缩写,更常用。

多环境配置

Profile 文件命名

Spring Boot 支持通过 Profile 管理多环境配置:

application.yml              # 默认配置
application-dev.yml          # 开发环境
application-test.yml         # 测试环境
application-prod.yml         # 生产环境

示例配置

application.yml - 默认配置:

server:
  port: 8080

spring:
  application:
    name: demo
  profiles:
    active: dev
    
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver

application-dev.yml - 开发环境:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo_dev
    username: root
    password: dev_password
    
logging:
  level:
    com.example: DEBUG

application-prod.yml - 生产环境:

server:
  port: 80
  
spring:
  datasource:
    url: jdbc:mysql://prod-db:3306/demo_prod
    username: prod_user
    password: ${DB_PASSWORD}
    
logging:
  level:
    com.example: INFO

激活 Profile

方式一:配置文件中指定

spring:
  profiles:
    active: dev

方式二:命令行参数

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

方式三:环境变量

export SPRING_PROFILES_ACTIVE=prod
java -jar demo.jar

方式四:Maven 构建时指定

mvn clean package -Dspring.profiles.active=prod

Profile 分组

Spring Boot 4 支持 Profile 分组:

spring:
  profiles:
    group:
      development: dev,h2,debug
      production: prod,mysql,monitoring

使用:

java -jar demo.jar --spring.profiles.active=development

外部化配置

配置加载顺序

Spring Boot 按照以下顺序加载配置(优先级从高到低):

  1. 命令行参数
  2. SPRING_APPLICATION_JSON 中的属性
  3. ServletConfig 初始化参数
  4. ServletContext 初始化参数
  5. JNDI 属性
  6. Java 系统属性(System.getProperties())
  7. 操作系统环境变量
  8. RandomValuePropertySource
  9. jar 包外的 application-{profile}.yml
  10. jar 包内的 application-{profile}.yml
  11. jar 包外的 application.yml
  12. jar 包内的 application.yml
  13. @PropertySource 注解
  14. 默认属性

使用环境变量

spring:
  datasource:
    url: jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:demo}
    username: ${DB_USERNAME:root}
    password: ${DB_PASSWORD:default_password}

使用命令行参数

java -jar demo.jar --server.port=9090 --spring.datasource.url=jdbc:mysql://new-host:3306/demo

@Value 注入配置

@Component
public class ConfigComponent {
    
    @Value("${server.port:8080}")
    private int port;
    
    @Value("${spring.application.name}")
    private String appName;
    
    @Value("${custom.property:default}")
    private String customProperty;
}

@ConfigurationProperties

推荐的方式,类型安全:

@ConfigurationProperties(prefix = "app")
@Component
@Data
public class AppProperties {
    
    private String name;
    private String version;
    private String description;
    
    private Security security = new Security();
    
    @Data
    public static class Security {
        private String secretKey;
        private int tokenExpire;
        private List<String> whiteList = new ArrayList<>();
    }
}

使用:

app:
  name: Demo Application
  version: 1.0.0
  description: Spring Boot 4 Demo
  security:
    secret-key: my-secret-key
    token-expire: 3600
    white-list:
      - /api/public
      - /api/health

注入:

@RestController
public class ConfigController {
    
    private final AppProperties appProperties;
    
    public ConfigController(AppProperties appProperties) {
        this.appProperties = appProperties;
    }
    
    @GetMapping("/api/config")
    public AppProperties getConfig() {
        return appProperties;
    }
}

配置加密

使用 Jasypt

1. 添加依赖

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

2. 配置加密密码

jasypt:
  encryptor:
    password: ${JASYPT_PASSWORD:my-secret-password}

3. 加密配置值

# 生成加密值
java -cp jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI \
  input="123456" password=my-secret-password algorithm=PBEWithMD5AndDES

4. 使用加密配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo
    username: root
    password: ENC(xxxxxxx)

配置验证

使用 JSR-303 验证

@ConfigurationProperties(prefix = "app")
@Component
@Data
@Validated
public class AppProperties {
    
    @NotBlank
    private String name;
    
    @NotNull
    @Min(1)
    @Max(100)
    private Integer version;
    
    @Email
    private String adminEmail;
}

启动时会验证配置,如果配置不合法会抛出异常。

配置热更新

使用 @RefreshScope

结合 Spring Cloud Config 实现配置热更新:

@RestController
@RefreshScope
public class ConfigController {
    
    @Value("${app.config:default}")
    private String config;
    
    @GetMapping("/api/config")
    public String getConfig() {
        return config;
    }
}

调用 /actuator/refresh 端点刷新配置:

curl -X POST http://localhost:8080/actuator/refresh

配置最佳实践

1. 敏感配置使用环境变量

spring:
  datasource:
    password: ${DB_PASSWORD}
  redis:
    password: ${REDIS_PASSWORD}

2. 使用@ConfigurationProperties

@ConfigurationProperties(prefix = "app")
@Component
public class AppProperties {
    // 类型安全的配置
}

3. 合理拆分配置文件

# application.yml - 通用配置
spring:
  profiles:
    active: dev

# application-dev.yml - 开发环境
# application-prod.yml - 生产环境

4. 配置文档化

# application.yml
server:
  port: 8080  # 服务端口

spring:
  application:
    name: demo  # 应用名称
  datasource:
    url: jdbc:mysql://localhost:3306/demo  # 数据库连接

5. 使用配置模板

# application.template.yml
spring:
  datasource:
    url: jdbc:mysql://${DB_HOST}:${DB_PORT}/${DB_NAME}
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}

总结

Spring Boot 配置管理要点:

良好的配置管理能让应用更加灵活、安全、易维护。


分享这篇文章到:

上一篇文章
Spring Boot CI/CD 流水线实战
下一篇文章
网关限流实战