gpt4 book ai didi

spring-boot - 如何使用Binder反序列化为Kotlin数据类?

转载 作者:行者123 更新时间:2023-12-05 06:36:19 24 4
gpt4 key购买 nike

我使用的是 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

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

最佳答案

也许这个引用会有所帮助,尝试在定义数据类时添加 @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

关于spring-boot - 如何使用Binder反序列化为Kotlin数据类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49189434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com