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
}