Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create map of lists from Spring config in Kotlin

I am trying to create a object of type Map<String, List<String>> in a Spring Boot application written in Kotlin.

I am able to create a map from config, and am also able to create a list from config, but when I try and combine the two I get the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myConfiguration': Could not bind properties to MyConfiguration (prefix=, ignoreInvalidFields=false, ignoreUnknownFields=true, ignoreNestedProperties=false); nested exception is java.lang.NullPointerException

My Configuration Object:

@ConfigurationProperties
@Component
class MyConfiguration {
   var myNewMap: Map<String, List<String>>? = null
}

My Configuration yml:

---
myNewMap:
   firstKey:
     - 2
     - 4
   secondKey:
     - 2

Is this possible with the way Spring reads in configuration? Or is the only way to create a simple Map with the values as a comma separated string, and turn it into a list in my application?

Kotlin: 1.2.0 Spring Boot: 1.5.6.RELEASE

like image 879
petarkolaric Avatar asked Dec 15 '17 03:12

petarkolaric


1 Answers

It works fine for me when the map is inside a "prefix" which is recommended for spring boot configurations.

My yml:

apiconfig:
  myNewMap:
    firstKey:
      - 2
      - 4
    secondKey:
      - 2

and my config class:

@Component
@ConfigurationProperties(prefix = "apiconfig")
class ApiConfiguration {
    var myNewMap: Map<String, List<String>>? = null
}

usage class:

@RestController
class Apis(@Autowired private val apiConfiguration : ApiConfiguration) {
    @GetMapping("/test")
    fun test(): String {
        apiConfiguration.myNewMap
        return "test"
    }
}
like image 90
bschandramohan Avatar answered Oct 13 '22 16:10

bschandramohan