我想根据我的属性文件中设置的密钥名称从AWS Secret Manager中检索数据库密码。但是,似乎无法像我希望的那样从application.yml
文件中读取属性。在下面的代码中,my.project.aws-secret
和my.project.region
都被检索为null
。
我是否期望此时可以检索到这些属性?这是实现此目标的正确方法,还是有更简单的方法?
这是代码。我目前正在尝试使用ApplicationListener
来做到这一点,但是我也看到了将其实现为EnvironmentPostProcessor
的相同问题:
ApplicationListener
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
}
application.yml
lots:
of:
properties: ...
my:
project:
aws-secret: the-name-of-the-secret-in-aws
region: us-east-1