java - 如何从 AWS 参数存储中获取 spring datasource 属性值?
问题描述
在我的 Spring Boot 应用程序中,我在 application.properties 文件中维护了 spring.datasource.url。我需要保护 URL/用户和密码,并且这些值在 AWS 参数存储中可用。我参考了这个文档,只是简单地添加了对( spring-cloud-starter-aws-parameter-store-config )启动模块的依赖来激活支持。我实际上不知道如何维护配置参数以及如何将参数存储值检索到我的项目中。
如果不使用以下 (application.properties) 属性中的硬编码值,如何实现这一点?
spring.datasource.url= url
spring.datasource.username = root
spring.datasource.password = xxxxxx
解决方案
要PropertySource
在 Spring Boot 应用程序中使用 AWS System Manager Parameter Store,请执行以下步骤。
将以下依赖项添加到build.gradle
:
dependencyManagement {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Greenwich.SR3'
}
}
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-aws-parameter-store-config'
}
添加到src/main/resources/bootstrap.properties
指定应用程序名称的属性:
spring.application.name=my-app
默认情况下,Spring Cloud AWS 依赖DefaultAWSCredentialsProviderChain和DefaultAwsRegionProviderChain。
如果应用程序不在EC2/Fargate 实例上运行,请通过设置以下环境变量来配置 AWS 凭证和区域:
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=us-west-1
或者确保您拥有有效的 AWS 配置文件~/.aws/credentials
和~/.aws/config
.
在 AWS System Manager Parameter Store 中定义以下属性:
/config/my-app/spring.datasource.url
/config/my-app/spring.datasource.username
/config/my-app/spring.datasource.password