我试图在Kotlin中为我的数据模型添加验证,使用@field
批注很容易做到简单的字段。但是,我正在努力对收藏进行同样的处理。
我已将问题上传到github here
Java模型没有问题,但kotlin版本没有问题。我在这里添加两个模型。
public class JavaUser {
@NotEmpty
@NotNull
@Pattern(regexp = "[a-z]*", message = "Only lower case first name")
private String name;
private List<
@NotNull
@NotEmpty
@Pattern(regexp = "\\d{10}", message = "Only 10 digits")
String> phones;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhones() {
return phones;
}
public void setPhones(List<String> phones) {
this.phones = phones;
}
}
data class KotlinUser(
@field:NotEmpty
@field:NotNull
@field:Pattern(regexp = "[a-z]*", message = "Only lower case first name")
val name: String,
// Cannot use @field here, anything else we could use?
val phones: List<
@NotNull
@NotEmpty
@Pattern(regexp = "\\d{10}", message = "Only 10 digits")
String>
)
我的测试-Java测试通过,但Kotlin测试失败
@Test
fun `java user validation`() {
val javaUser = JavaUser()
javaUser.name = "sadfjsjdfhsjdf"
javaUser.phones = listOf("dfhgd")
webTestClient.put().uri("/user/java")
.body(BodyInserters.fromObject(javaUser))
.exchange()
.expectStatus().is4xxClientError
}
@Test
fun `kotlin user validation`() {
val kotlinUser = KotlinUser(name = "sadfjsjdfhsjdf", phones = listOf("dfhgd"))
webTestClient.put().uri("/user/kotlin")
.body(BodyInserters.fromObject(kotlinUser))
.exchange()
.expectStatus().is4xxClientError
}
Controller
@RestController
class Controller {
@PutMapping("/user/java")
fun putUser(@RequestBody @Valid javaUser: JavaUser): Mono<ResponseEntity<String>> =
Mono.just(ResponseEntity("shouldn't get this", HttpStatus.OK))
@PutMapping("/user/kotlin")
fun putUser(@RequestBody @Valid kotlinUser: KotlinUser): Mono<ResponseEntity<String>> =
Mono.just(ResponseEntity("shouldn't get this", HttpStatus.OK))
}
任何帮助将不胜感激。谢谢!
最佳答案
当前不支持此功能。 Kotlin编译器当前忽略类型的注释。
详情请参阅:
在Kotlin问题追踪器上也有与此相关的问题:
后者具有目标版本
1.4
。
关于validation - 我们如何在Collection上进行kotlin数据类验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870571/