扩展Hibernate-Validator的ConstraintValidator默认实现
注意:本文是修改已有javax.validation.constraints注解的默认实现
,如:修改@NotNull,NotNullValidator的实现,而非扩展自定义注解,对于自定义注解的场景,本文不做说明。
一、实现
- 自定义@NotNull的校验器
package com.yxiao.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.NotNull;
public class CustomNotNullValidator implements ConstraintValidator<NotNull, Object> {
@Override
public void initialize(NotNull constraintAnnotation) {
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
// 校验逻辑....
}
}
- 注入Validator,替换@NotNull实现
package com.yxiao.config;
import com.yxiao.validator.CustomNotNullValidator;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.cfg.ConstraintMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
@Configuration
public class ValidatorConfig {
@Bean
public Validator validator() {
// 获取配置
HibernateValidatorConfiguration configure = Validation.byProvider(HibernateValidator.class).configure();
// 创建ConstraintMapping
ConstraintMapping constraintMapping = configure.createConstraintMapping();
// 新增@NotNull的约束
constraintMapping.constraintDefinition(NotNull.class)
// 设置自定义的校验器
.validatedBy(CustomNotNullValidator.class)
// 配置false,忽略HibernateValidator默认校验器NotNullValidator
.includeExistingValidators(false);
Validator validator = configure
.failFast(true)
.addMapping(constraintMapping)
.buildValidatorFactory()
.getValidator();
return validator;
}
}