springspring-bootkotlinspring-dsl

How to access Environment properties in the beans element of the Bean Definition DSL using Spring 5 and Kotlin


I want to define some beans depending on the values of some properties from the application.yml file of a Spring Boot Application. For instance with a number-of-beans: 5 I build a for loop to create 5 bean instances:

application.yml

number-of-beans: 5

BeanDsl.kt

fun beans() = beans {
    val n = env.getProperty("number-of-beans")
    for (i in 1..n) {
        bean<String>("string${i}") { "string${i}" }
    } 
}

The problem is how to access the environment at that point since the env variable isn't available there. It's funny it is inside the bean{} element.


Solution

  • It is not possible with Spring Framework 5.0, but I have just added such support via this commit, this improvement will be available as of Spring Framework 5.1 / Spring Boot 2.1.