我有一个实体:

class SomeInfo(
        @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX) var value: String) {
    var id: Long? = null
}

和控制器方法:

@RequestMapping(value = "/some-info", method = RequestMethod.POST)
public Id create(@Valid @RequestBody SomeInfo someInfo) {
       ...
    }

@Valid annotation doesn't work.

It seems Spring needs a default parameterless constructor and fancy code above becomes in something ugly (but working) like this:

class SomeInfo() {

    constructor(value: String) {
            this.value = value
        }

        @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX) 
        lateinit var value: String

        var id: Long? = null
    }

Any good practice to make it less wordy?

谢谢.

推荐答案

Seems Spring needs these annotations to be applied to a field. But Kotlin will apply these annotations to the constructor parameter. Use field: specifier when applying an annotation to make it apply to a field. The following code should work fine for you.

class SomeInfo(
    @field:NotNull
    @field:Pattern(regexp = Constraints.EMAIL_REGEX)
    var value: String
) {
    var id: Long? = null
}

Kotlin相关问答推荐

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

API迁移到Spring Boot 3后,Spring Security无法工作

kotlin中如何使用子类调用父静态方法?

try 一次性插入多条记录时,JOOQ连接为空错误

gradle 如何 Select 以-jvm结尾的库?

如何将 `throw` 放置在辅助函数中但仍然具有空安全性?

在 Kotlin 中,我可以在集合上有一个条件构建器元素吗?

kotlin 单例异常是好是坏?

Kotlin 中获取类简单名称的最佳实践

为什么没有remember 的 mutableStateOf 有时会起作用?

Gradle 同步失败:不支持的方法:KotlinPlatformContainer.supports()

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

以编程方式重新启动 Spring Boot 应用程序/刷新 Spring 上下文

如何在Spring Boot应用程序上启用承载身份验证?

更新到版本4.10.1/4.10.2后 Gradle 同步失败

Kotlin:什么是 kotlin.String!类型

在 Kotlin 中返回函数有不那么丑陋的方法吗?

使用 java lambda 调用 kotlin 函数时,Kotlin 无法访问 kotlin.jvm.functions.Function1

目前不支持 Gradle 项目的自动库版本更新.请手动更新您的 build.gradle

java.lang.NoClassDefFoundError:解析失败:Lkotlin/time/MonoClock