【问题标题】:Create map of lists from Spring config in Kotlin在 Kotlin 中从 Spring 配置创建列表映射
【发布时间】:2018-05-29 05:55:51
【问题描述】:

我正在尝试在用Kotlin 编写的Spring Boot 应用程序中创建Map<String, List<String>> 类型的对象。

我能够从配置创建地图,也能够从配置创建列表,但是当我尝试将两者结合起来时,出现以下异常:

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

我的Configuration Object

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

我的Configuration yml

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

这可能与 Spring 读取配置的方式有关吗?或者是用逗号分隔的字符串创建一个简单的 Map 并将其转换为我的应用程序中的列表的唯一方法?

Kotlin: 1.2.0 Spring Boot: 1.5.6.RELEASE

【问题讨论】:

    标签: spring spring-boot kotlin yaml


    【解决方案1】:

    对于仍然有这个的人,@Component 接口对你没有帮助,你需要@ConstructorBinding

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

    【讨论】:

      【解决方案2】:

      当地图位于推荐用于 Spring Boot 配置的“前缀”内时,它对我来说很好。

      我的 yml:

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

      和我的配置类:

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

      使用类:

      @RestController
      class Apis(@Autowired private val apiConfiguration : ApiConfiguration) {
          @GetMapping("/test")
          fun test(): String {
              apiConfiguration.myNewMap
              return "test"
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-05-13
        • 2019-09-11
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多