Spring Boot Custom Validator

Usage

Kotlin

方案一:ConstraintValidator

注意:Controller必须加上@Validated

  • Define Validator Class

    1
    2
    3
    4
    5
    6
    7
    8
    9
    class OrderConstraintValidator : ConstraintValidator<OrderValidatorAnnotation, Order> {

    override fun isValid(order: Order?, context: ConstraintValidatorContext?): Boolean {
    context?.disableDefaultConstraintViolation()
    context?.buildConstraintViolationWithTemplate("order is null")
    ?.addConstraintViolation()
    return true
    }
    }
  • Define Validator Annotation

    1
    2
    3
    4
    5
    6
    7
    8
    @Target(AnnotationTarget.VALUE_PARAMETER)
    @Retention(AnnotationRetention.RUNTIME)
    @Constraint(validatedBy = [OrderConstraintValidator::class])
    annotation class OrderValidatorAnnotation(
    val message: String = "",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = []
    )
  • Handle ConstraintViolationException

1
2
3
//  消息的处理可以放在@ControllerAdvice里面
// 获取自定义错误消息 -> "order is null"
val message = ex.constraintViolations.iterator().next().message

CustomValidatorBean

对应注解@Valid,等于覆盖框架的校验逻辑

1
2
3
4
5
6
7
8
9
class OrderValidatorBean : CustomValidatorBean() {
override fun supports(clazz: Class<*>): Boolean {
return Order::class.isInstance(clazz)
}

override fun validate(target: Any?, errors: Errors) {
super.validate(target, errors)
}
}