跳到主要内容

属性源

DeepSeek V3 中英对照 Property Sources

Vault 可以在许多不同的场景中使用。一个特定的用例是使用 Vault 来存储加密的属性。Spring Vault 支持将 Vault 作为属性源,通过 Spring 的 PropertySource 抽象 来获取配置属性。

备注

你可以引用存储在 Vault 中的属性到其他属性源中,或者使用 @Value(…) 进行值注入。在引导需要存储在 Vault 中的数据的 bean 时,需要特别注意。此时必须初始化一个 VaultPropertySource 以便从 Vault 中检索属性。

备注

Spring Boot/Spring Cloud 用户可以利用 Spring Cloud Vault 的配置集成,该集成在应用程序启动期间初始化各种属性源。

注册 VaultPropertySource

Spring Vault 提供了一个 VaultPropertySource,用于与 Vault 结合使用以获取属性。它使用嵌套的 data 元素来暴露存储在 Vault 中并加密的属性。

ConfigurableApplicationContext ctx = new GenericApplicationContext();
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.addFirst(new VaultPropertySource(vaultTemplate, "secret/my-application"));
java

在上面的代码中,VaultPropertySource 已被添加到搜索中的最高优先级。如果它包含一个 foo 属性,它将被检测并优先于任何其他 PropertySource 中的 foo 属性返回。MutablePropertySources 提供了许多方法,允许对属性源集进行精确操作。

@VaultPropertySource

@VaultPropertySource 注解提供了一种便捷且声明式的机制,用于将 PropertySource 添加到 Spring 的 Environment 中,以便与 @Configuration 类一起使用。

@VaultPropertySource 接受一个 Vault 路径,例如 secret/my-application,并将存储在该节点中的数据暴露在 PropertySource 中。@VaultPropertySource 支持对与租约关联的密钥(例如来自 mysql 后端的凭证)进行租约续期,并在租约最终到期时进行凭证轮换。默认情况下,租约续期是禁用的。

示例 1. 存储在 Vault 中的属性

{
// …

"data": {
"database": {
"password": ...
},
"user.name": ...,
}

// …
}
json

示例 2. 声明一个 @VaultPropertySource

@Configuration
@VaultPropertySource("secret/my-application")
public class AppConfig {

@Autowired Environment env;

@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setUser(env.getProperty("user.name"));
testBean.setPassword(env.getProperty("database.password"));
return testBean;
}
}
java

示例 3. 声明一个带有凭证轮换和前缀的 @VaultPropertySource

@Configuration
@VaultPropertySource(value = "aws/creds/s3-access",
propertyNamePrefix = "aws.",
renewal = Renewal.ROTATE)
public class AppConfig {
// provides aws.access_key and aws.secret_key properties
}
java
备注

generic 密钥后端获取的密钥与 TTL(refresh_interval)相关联,但不与租约 ID 相关联。Spring Vault 的 PropertySource 在达到 TTL 时会轮换 generic 密钥。

备注

你可以使用 @VaultPropertySource 从版本化的 Key-Value 后端获取最新的秘密版本。确保路径中不包含 data/ 部分。

@VaultPropertySource 路径中出现的任何 ${…​} 占位符都会根据环境中已经注册的属性源集合进行解析,如下例所示:

示例 4. 使用占位符声明 @VaultPropertySource 路径

@Configuration
@VaultPropertySource(value = "aws/creds/${my.placeholder:fallback/value}",
propertyNamePrefix = "aws.",
renewal = Renewal.ROTATE)
public class AppConfig {
}
java

假设 my.placeholder 已经存在于已注册的某个属性源中(例如系统属性或环境变量),占位符将被解析为相应的值。如果没有找到,则使用 fallback/value 作为默认值。如果没有指定默认值且无法解析该属性,则会抛出 IllegalArgumentException

在某些情况下,使用 @VaultPropertySource 注解时,可能无法或不便严格控制属性源的顺序。例如,如果上述 @Configuration 类是通过组件扫描注册的,顺序将难以预测。在这种情况下——如果覆盖顺序很重要——建议用户转而使用编程式的 PropertySource API。有关详细信息,请参阅 ConfigurableEnvironmentMutablePropertySources