【问题标题】:How to use Binder to deserialize to Kotlin's data class?如何使用 Binder 反序列化为 Kotlin 的数据类?
【发布时间】:2018-03-09 08:23:57
【问题描述】:

我使用 SpringBoot2.0.0.RELEASE、Kotlin 1.2.30、Java9。

我在配置文件中有如下配置:

test:
  user:
    id: 111
    username: 111
    password: 111
    addtime: 2018-11-11 11:11:11

User.kt代码如下:

data class User(
        val id: String,
        val username: String,
        val password: String,
        val addtime: LocalDateTime
) : Serializable

我尝试使用以下代码读取配置:

Binder.get(this.context.environment)
        .bind("test.user", User::class)
        .orElse(null)

但是没有成功,返回如下错误:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [demo.User]: Illegal arguments for constructor; nested exception is java.lang.IllegalArgumentException: No argument provided for a required parameter: parameter #0 id of fun <init>(kotlin.String, kotlin.String, kotlin.String, java.time.LocalDateTime): demo.User
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:179)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:124)
    at org.springframework.boot.context.properties.bind.JavaBeanBinder$Bean.lambda$getSupplier$0(JavaBeanBinder.java:173)
    at org.springframework.boot.context.properties.bind.JavaBeanBinder$BeanSupplier.get(JavaBeanBinder.java:227)
    at org.springframework.boot.context.properties.bind.JavaBeanBinder$BeanProperty.lambda$getValue$0(JavaBeanBinder.java:303)
    ... 80 more

完整的错误日志:https://gist.github.com/Cat7373/174b0ddaf103b35062e7b03982f8cb38

我怎样才能成功?感谢您的帮助。

【问题讨论】:

    标签: spring-boot kotlin


    【解决方案1】:

    也许这个参考会有所帮助,在定义数据类时尝试添加@PersistentConstructor 注释:Spring constructor annotations on Kotlin data class with default values 或者,尝试为每个属性设置默认值。例如:

    data class User(
        val id: String = "",
        val username: String = "",
        val password: String = "",
        val addtime: LocalDateTime = LocalDateTime.now()
    ) : Serializable
    

    【讨论】:

    • enum等一些参数可能没有合适的默认参数,所以这样做可能不太合适
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多