Spring 配置外部化
配置外部化是云原生应用的核心特性——应用程序制品在部署到不同环境时保持不变,通过外部配置实现差异化。
核心原则
不要将凭据与应用程序代码一起存储。同一构建产物部署到不同环境时,使用不同的配置数据,无需重新构建。
Spring Properties 配置
属性来源优先级
| 优先级 | 来源 | 说明 |
|---|---|---|
| 1 | @TestPropertySource | 测试类注解 |
| 2 | 命令行参数 | --server.port=9000 |
| 3 | JVM 系统属性 | System.getProperties() |
| 4 | 环境变量 | System.getenv() |
| 5 | 配置文件 | application.yml/properties |
| 6 | @ConfigurationPropertySource | 自定义配置源 |
| 7 | SpringApplication.setDefaultProperties | 默认属性 |
配置文件优先级
| 优先级 | 位置 | 文件 |
|---|---|---|
| 1 | JAR 外部 | application-{profile}.yml |
| 2 | JAR 外部 | application.yml |
| 3 | JAR 内部 | application-{profile}.yml |
| 4 | JAR 内部 | application.yml |
访问属性的方式
// 1. Environment 接口(通用方式)
@Autowired
private Environment environment;
environment.getProperty("server.port");
// 2. @Value 注解(直接注入)
@Value("${server.port}")
private String serverPort;
// 3. @ConfigurationProperties(推荐方式)
@ConfigurationProperties(prefix = "polar")
public record PolarProperties(String greeting) {}
// 使用
@RestController
public class HomeController {
private final PolarProperties polarProperties;
public HomeController(PolarProperties polarProperties) {
this.polarProperties = polarProperties;
}
@GetMapping("/")
public String getGreeting() { return polarProperties.greeting(); }
}Spring Profiles
Profile 是 Spring 的特性标志和配置分组机制。
Profile 用作特性标志
@Component
@Profile("test-data")
public class BookDataLoader {
@EventListener(ApplicationReadyEvent.class)
public void loadBookTestData() {
bookRepository.save(new Book("1234567891", "Northern Lights", "Lyra", 9.90));
}
}激活方式:
spring:
profiles:
active: test-dataProfile 用作配置分组
application.yml # 默认配置
application-dev.yml # 开发环境覆盖
application-prod.yml # 生产环境覆盖注意
Profile 命名建议
- 避免使用 dev/prod 作为 Profile 名
- 使用功能名称命名(如 test-data、kubernetes)
- Profile 代表功能,与环境解耦
外部化配置方式对比
| 方式 | 适用场景 |
|---|---|
| 应用内属性文件 | 定义默认值,面向开发环境 |
| 环境变量 | 基础设施配置(主机名、端口),跨语言通用 |
| Config Server | 配置持久化、审核、加密、动态刷新 |
Spring Cloud Config Server
| 特性 | 说明 |
|---|---|
| Git 后端存储 | 配置版本化,支持回滚 |
| REST API | 客户端通过 HTTP 获取配置 |
| 加密支持 | 敏感配置加密存储 |
| 动态刷新 | 无需重启应用 |
| 多环境支持 | 通过 profile 区分环境 |
客户端设置
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-config'
}# bootstrap.yml
spring:
cloud:
config:
uri: http://localhost:8888
fail-fast: true
retry:
max-attempts: 6
multiplier: 1.5配置刷新
curl -X POST http://localhost:9001/actuator/refresh配置管理方案选型
| 场景 | 推荐方案 | 原因 |
|---|---|---|
| 开发环境默认值 | 应用内配置 | 简单方便 |
| 基础设施配置 | 环境变量 | 平台标准化 |
| 多环境差异 | Config Server + Git | 集中管理、版本控制 |
| 敏感信息 | Config Server 加密 | 安全合规 |
| 功能开关 | Config Server | 动态控制 |
常用配置示例
spring:
datasource:
url: ${DATABASE_URL}
username: ${DATABASE_USERNAME}
password: ${DATABASE_PASSWORD}
server:
port: ${PORT:8080}
logging:
level:
root: ${LOG_LEVEL:INFO}