Home > Net >  Spring read list property dynamically
Spring read list property dynamically

Time:07-12

With spring it easily possible to read a normal property using env.getProperty(key)

For example if your application.yaml looks like this:

test: "a"

You can read the value like this:

val test = env.getProperty("test")

But now assume you want to read the following application.yaml:

test:
  - 
    a: "a"
  - 
    b: "b"

How can I read test[a] dynamically?

What does not work unfortunately is this:

val test = env.getProperty("test[a]")

CodePudding user response:

The given yaml structure would map to list of object. If you want to access the environment variables using env then following would work

val a = env["test[0].a"] // a
val b = env["test[1].b"] // b

Note that the objects within the list have to be accessed with index.

Alternatively, if you are using spring, you can define a ConfigurationProperties class and map all the values to the class variable

@ConfigurationProperties 
class ConfigProperties (val test: List<Map<String, String>>)

You can inject this class in required code and access the required property by iterating over the list

@Component
class TempService(val configProperties: ConfigProperties){
    fun temp(){
        val a: String = configProperties.test.firstNotNullOf { it["a"] }
    }
}

Ideal solution would be to change the yaml structure to normal nested object

  • Related