缺少无参数的构造函数,但应该存在

时间:2019-12-18 15:11:26

标签: spring-boot maven intellij-idea kotlin compilation

在Spring Boot应用程序中,我有一个实体类,它没有no-arg构造函数,但具有初始化的字段。

@Entity
@Table(name = "users")
data class User(
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        var id: Long? = null,
        @Column(name = "username", unique = true, nullable = false)
        var username: String = "",
        @Column(name = "password", nullable = false)
        var password: String = "",
        @Column(name = "language")
        var language: String? = null,
        @ManyToMany(fetch = FetchType.EAGER)
        @JoinTable(name = "user_role", joinColumns = [JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)], inverseJoinColumns = [JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false)])
        var roles: Set<Role> = HashSet(),
        @OneToOne
        @JoinColumn(name = "active_profile")
        var activeProfile: ExchangeProfile? = null
)

然后我有一个通用方法来创建这些类的实例:

private fun createNewInstance(): T = itemClass.createInstance()

正如我所读的,编译器应该生成no-arg构造函数,并且这段代码应该没有问题。 使用“运行配置”按钮在IntelliJ Idea中运行此代码可以正常工作。

但是使用

从控制台运行它
mvn clean compile spring-boot:run

(或在docker中)引发异常:

Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Class should have a single no-arg constructor: class com.iwaneez.stuffer.core.persistence.entity.User
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:213) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:308) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
        ... 75 common frames omitted
Caused by: java.lang.IllegalArgumentException: Class should have a single no-arg constructor: class com.iwaneez.stuffer.core.persistence.entity.User
        at kotlin.reflect.full.KClasses.createInstance(KClasses.kt:281) ~[kotlin-reflect-1.3.61.jar:1.3.61-release-180 (1.3.61)]
        at com.iwaneez.stuffer.core.ui.component.masterdetail.DetailComponent.createNewInstance(DetailComponent.kt:104) ~[classes/:na]

您有什么想法,如何在不显式定义无参数构造函数的情况下进行修复?

0 个答案:

没有答案