跳到主要内容
版本:4.1.0

属性源

Doubao 中英对照 Property Sources

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

备注

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

备注

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

备注

Vault 通过 Vault 的 sys/internal/ui/mounts/… 端点确定挂载路径。请确保你的策略允许访问该路径,否则你将无法使用 Vault 属性源。

注册 VaultPropertySource​

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

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

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

@VaultPropertySource​

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

@VaultPropertySource 接收一个 Vault 路径(例如 secret/my-application),并将存储在该节点的数据暴露在 PropertySource 中。@VaultPropertySource 支持与租约关联的机密的租约续期(例如来自 mysql 机密引擎的凭据),以及在终端租约到期时进行凭据轮换。租约续期默认禁用。

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

{
// …

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

// …
}

示例 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;
}
}

示例 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
}
备注

从 generic 机密引擎获得的机密与 TTL(refresh_interval)相关联,但没有租约 Id。Spring Vault 的 PropertySource 在达到其 TTL 时轮换通用机密。

备注

你可以使用 @VaultPropertySource 从有版本的 Key-Value 机密后端获取最新的机密版本。请确保不要在路径中包含 data/ 段。

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

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

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

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

在某些情况下,使用 @VaultPropertySource 注解时,可能无法或不切实际地严格控制属性源顺序。例如,如果上面的 @Configuration 类是通过组件扫描注册的,则顺序很难预测。在这种情况下——如果覆盖很重要——建议用户回退到使用编程式 PropertySource API。有关详细信息,请参阅 ConfigurableEnvironment 和 MutablePropertySources。