kotlin 和 @Valid Spring 注释 [英] kotlin and @Valid Spring annotation
本文介绍了kotlin 和 @Valid Spring 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实体:
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
注释不起作用.
似乎 Spring 需要一个默认的无参数构造函数,上面花哨的代码变得像这样丑陋(但有效):
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?
谢谢.
推荐答案
似乎 Spring 需要将这些注释应用于一个字段.但是 Kotlin 会将这些注解应用到构造函数参数上.在应用注释时使用 field:
说明符使其适用于字段.以下代码应该适合您.
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 和 @Valid Spring 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文