具有默认值的Kotlin数据类上的Spring构造函数注释 [英] Spring constructor annotations on Kotlin data class with default values

查看:113
本文介绍了具有默认值的Kotlin数据类上的Spring构造函数注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要使用spring持久性但要保持不可变的类型,我已经在我的数据类中添加了PersistenceConstructor注释.这告诉spring从数据库加载类时要使用该构造函数.

To use spring persistence but maintain immutable types I've added the PersistenceConstructor annotation to my data classes. This tells spring to use that constructor when loading classes from the database.

但是,我很难找到弹簧来寻找构造函数.

However, I'm having trouble getting spring to find the constructor.

data class MyData @PersistenceConstructor constructor(@Id val id: Int? = null, val a:String)

这在我的机器上100%的时间有效,但是当部署到heroku时,它始终会失败.

This works 100% of the time on my machine but when deployed to heroku it consistently fails.

看起来,通过让参数具有默认值,kotlin可以生成多个构造函数,但是问题是每个构造函数都会将注释应用到它们,因此运气(或特定于jdk的实现)仅是一个春天就可以了.默认的参数没有名称,因此Spring不知道如何处理.

It looks like, by having default values for parameters kotlin generates more than one constructors but the problem is that each constructor get the annotation applied to them so it's just luck (or jdk implementation specific) which one spring picks up. The default one has no names for the parameters so Spring doesn't know what to do with it.

我的实际构造函数大于此构造函数,因此如果没有默认值将很痛苦.有没有一种方法可以使注释仅适用于没有默认值的构造函数?

My real constructors are larger than this so it would be a pain to not have default values. Is there a way to get the annotation to only apply to the constructor without default values?

推荐答案

目前,我当前的答案是定义两个构造函数.一个供我使用的具有默认值,另一个供我使用的弹簧具有默认值.

At the moment my current answer is to define two constructors. One for me to use that has defaults and one for spring to use that doesn't have defaults.

data class MyData @PersistenceConstructor constructor(val a: Int?, val b:String, val c : Collection<Int>) {
  constructor(a: Int? = null, b: String = "", c: Collection<Int> = emptyList()) : this(a,b,c)
}

我不喜欢将其作为重复项,因此它不是我的首选解决方案.

I don't like it as its duplication so it's not my preferred solution.

这篇关于具有默认值的Kotlin数据类上的Spring构造函数注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆