Usage
Kotlin
方案一:ConstraintValidator
注意:Controller必须加上@Validated
Define Validator Class
1
2
3
4
5
6
7
8
9class 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(AnnotationTarget.VALUE_PARAMETER)
(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 | // 消息的处理可以放在@ControllerAdvice里面 |
CustomValidatorBean
对应注解@Valid,等于覆盖框架的校验逻辑
1 | class OrderValidatorBean : CustomValidatorBean() { |