SpringBoot Validation + Kotlin校验无效的解决方法

- 2 mins

DTO

package dawsonlee1790.springboot_validation_kotlin_demo.dto

import javax.validation.constraints.Max
import javax.validation.constraints.Pattern

/**
 * @author dawsonlee1790
 * @email dawsonlee1790@gamil.com
 * @date 2018-12-26
 */
data class LoginDTO(
        @field:Pattern(regexp = "[a-zA-Z0-9]+", message = "姓名只能由数字和大小写字母组成")
        val name: String,
        @get:Max(18, message = "居然超过18岁了,可怕,不允许")
        val age: Int
)

/*
//============springboot validation 不生效============
data class LoginDTO(
        @Pattern(regexp = "[a-zA-Z0-9]+", message = "姓名只能由数字和大小写字母组成")
        val name: String,
        @Max(18, message = "居然超过18岁了,可怕,不允许")
        val age: Int
)
*/

controller

package dawsonlee1790.springboot_validation_kotlin_demo.controller

import dawsonlee1790.springboot_validation_kotlin_demo.dto.LoginDTO
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * @author dawsonlee1790
 * @email dawsonlee1790@gamil.com
 * @date 2018-12-26
 */
@RestController
@RequestMapping("/loginController")
class LoginController {

    @PostMapping("/login")
    fun login(@RequestBody @Validated loginDTO: LoginDTO) {
        println("Hello ${loginDTO.name}!")
    }

}

原因分析

解决方案

项目源码

Dawson Lee

A man who loves to watch Korean dramas

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora