Skip to content

Instantly share code, notes, and snippets.

@grim13b
Created March 28, 2019 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grim13b/aa625fe5522385a6bafad59f407068eb to your computer and use it in GitHub Desktop.
Save grim13b/aa625fe5522385a6bafad59f407068eb to your computer and use it in GitHub Desktop.
SpringBootの起動時にCustomなPropertySourceを読み込ませる例
@SpringBootApplication
class Application
fun main(args: Array<String>) {
// SpringApplication.run(*args)
SpringApplicationBuilder(Application::class.java)
// ここで起動時に追加したい Initializer を渡す
.initializers(CustomContextInitializer())
.run(*args)
}
class CustomContextInitializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
private fun getSsmClient(): SsmClient {
val credentialsProvider = AwsCredentialsProviderChain.builder()
.credentialsProviders(
EnvironmentVariableCredentialsProvider.create(),
SystemPropertyCredentialsProvider.create(),
ProfileCredentialsProvider.create(),
ContainerCredentialsProvider.builder().build())
.build()
return SsmClient.builder()
.credentialsProvider(credentialsProvider)
.region(Region.AP_NORTHEAST_1)
.build()
}
override fun initialize(applicationContext: ConfigurableApplicationContext) {
val environment = applicationContext.environment
val propertySources = environment.propertySources
// これが今回最大のお仕事をする部分です。
// applicationContext にある PropertySource 群の「先頭」に SSM ParameterStore から取得してくる PropertySource を追加します。
propertySources.addFirst(
CustomPropertySource(
"ssmParamStorePropertySource",
CustomSource(getSsmClient())
)
)
}
}
class CustomPropertySource(name: String, source: CustomSource)
: PropertySource<CustomSource>(name, source) {
companion object {
const val SPLIT_CHARACTER = "/"
}
override fun getProperty(name: String): Any? {
return if (name.startsWith(SPLIT_CHARACTER)) {
source.getProperty(name)
} else null
}
}
class CustomSource(private val ssmClient: SsmClient) {
fun getProperty(propertyName: String): Any? {
try {
return ssmClient.getParameter(
GetParameterRequest.builder()
.name(propertyName)
.withDecryption(true)
.build())
.parameter()
.value()
} catch (e: ParameterNotFoundException) {
// 指定されたParameterが無い場合に飛んできます。適宜処理してください。
} catch (e: Exception) {
// 適宜処理してください。
}
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment