Kotlin & Spring boot 使用@Valid校验无效解决方法

kotlin data (对应java实体类

@Entity
@Table(name = "user")
data class User(
        @NotNull(message = "用户名不能为空")
        @Column(name = "user_name", nullable = false)
        var userName: String = "",

        @NotNull(message = "用户ID不能为空")
        @Column(name = "user_id", unique = true)
        var userId: String = "",

        @Email(message = "无效的邮箱")
        var email: String = "",

        @Column(nullable = false)
        var password: String = ""

) : Serializable 

再来看controller

@RestController
@RequestMapping("/user")
class UserController {

    @Autowired lateinit var userRepository: UserRepository

    @PutMapping(value = "/put",
     consumes = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE))
    @ResponseBody
    fun put(@Valid @RequestBody user: SysUser):
    ResponseEntity? {
        if (result.hasErrors()) {
            val fieldErrors = result.fieldErrors
            for (fieldError in fieldErrors) {
                println("${fieldError.defaultMessage}")
            }
            return fieldErrors
        }
        println(user)
        return ResponseEntity
                .ok()
                .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
                .eTag("AC") 
                .body(user)
    }
}

调用put方法,@Valid校验无效

原因分析:

在 java 中,将 validation 注解到实体类属性或者 get/set 方法上,但是在 kotlin 中,属性直接写在构造函数中,validation 注解并没有作用到属性上。

解决方法:

使用 @field: 标识符,field标识符只允许在属性的访问器函数内使用。它能够 validation 校验注解作用与属性。

将 kotlin data class 稍作修改:

@Entity
@Table(name = "user")
data class User(
        @field:NotNull(message = "用户名不能为空")
        @Column(name = "user_name", nullable = false)
        var userName: String = "",

        @field:NotNull(message = "用户ID不能为空")
        @Column(name = "user_id", unique = true)
        var userId: String = "",

        @field:NotBlank(message = "邮箱不能为空")
        @field:Email(message = "无效的邮箱")
        var email: String = "",

        @field:NotBlank(message = "密码不能为空")
        @Column(nullable = false)
        var password: String = ""

) : Serializable 

之后,@Valid校验即可正常工作

再次执行

curl -v http://localhost:8080/user/put

看到错误信息

{
  "timestamp": "2017-03-04 13:54:19",
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "field": "userId",
      "rejectedValue": null,
      "bindingFailure": false,
      "objectName": "sysUser",
      "codes": [
        "NotNull.sysUser.userId",
        "NotNull.userId",
        "NotNull.java.lang.String",
        "NotNull"
      ],
      "arguments": [
        {
          "codes": [
            "sysUser.userId",
            "userId"
          ],
          "arguments": null,
          "defaultMessage": "userId"
        }
      ],
      "defaultMessage": "用户ID不能为空"
    }
  ],
  "message": "Validation failed for object='sysUser'. Error count: 1",
  "path": "/user/put"
}

你可能感兴趣的:(kotlin)