我想根据我的属性文件中设置的密钥名称从 AWS Secret Manager 中检索我的数据库密码。然而,我似乎无法application.yml
像我希望的那样从文件中读取属性。在下面的代码中,my.project.aws-secret
和my.project.region
都被检索为null
.
我期望这些属性此时可以检索是错误的吗?这是实现这一目标的正确方法,还是有更简单的方法?
这是代码。我目前正在尝试使用 an 来执行此操作ApplicationListener
,但我也看到了同样的问题来实现它EnvironmentPostProcessor
:
应用程序监听器
public class DatasourceAwsProperties implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
Properties props = new Properties();
String datasourcePassword = environment.getProperty("my.project.aws-secret"); // why is this null?
String awsRegion = environment.getProperty("my.project.region"); // why is this null?
String secret = getSecret(datasourcePassword, awsRegion);
MapPropertySource newProperties = new MapPropertySource("newProperties", ImmutableMap.of("spring.datasource.password", secret));
environment.getPropertySources().addLast(newProperties);
}
public static String getSecret(String secretName, String region) {
// gets secret from aws
}
应用程序.yml
lots:
of:
properties: ...
my:
project:
aws-secret: the-name-of-the-secret-in-aws
region: us-east-1