Home > Net >  How to read properties as immutable strings in Kotlin
How to read properties as immutable strings in Kotlin

Time:01-26

I have been trying to read the read the properties in the Kotlin code. The lateinit var gets the work done but since it is mutable, the value can be changed even after initialisation. I want to read a property from a file and to not worry about it being changed anywhere in the file. I want something like lateinit val which is not present in Kotlin; or you somehow able to add @Value inside by lazy block of code.

I am working with AWS Secret Manager so I am putting the same code here but my doubt is more generic and not specific to AWS.

@Value("\${aws.secretsManager.region}")
private lateinit var region: String

@Bean(name = ["secretsManagerClient"])
fun secretsManagerClient(): SecretsManagerClient {
    return SecretsManagerClient.builder()
        .region(Region.of(region))
        .build()
}

I tried doing the similar thing with by lazy:

@Value("\${aws.secretsManager.region}")
private lateinit var region: String

private val awsRegion: Region by lazy {
    Region.of(region)
}

@Bean(name = ["secretsManagerClient"])
fun secretsManagerClient(): SecretsManagerClient {
    return SecretsManagerClient.builder()
        .region(awsRegion)
        .build()
}

The above codes are working fine but it would be much cleaner if there's a way to merge these 2 lines:

@Value("\${aws.secretsManager.region}")
private lateinit var region: String

private val awsRegion: Region by lazy {
    Region.of(region)
}

CodePudding user response:

In your specific case you can inject property directly into bean method as an argument (method arguments are immutable)

@Bean(name = ["secretsManagerClient"])
fun secretsManagerClient(
    @Value("\${aws.secretsManager.region}") region: String
): SecretsManagerClient {
    return SecretsManagerClient.builder()
        .region(Region.of(region))
        .build()
}

or if you need this property in multiple @Beans you can inject it into constructor of enclosing configuration class

@Confiuration
class SomeConfig(
    @Value("\${aws.secretsManager.region}")
    private val region: String
) {

    @Bean(name = ["secretsManagerClient"])
    fun secretsManagerClient(): SecretsManagerClient {
        return SecretsManagerClient.builder()
            .region(Region.of(region))
            .build()
    }
}   
  • Related