1.单独使用Hibernate-validator和Apache BVal
1)Apache BVal
@NotNull private Integer num; public Validator getValidatorFactory() { ValidatorFactory avf = Validation.byProvider(HibernateValidator.class).configure().buildValidatorFactory(); return avf.getValidator(); } Set<ConstraintViolation<T>> errorSet = getValidatorFactory().validateValue(t, "num",num , true));
2)Hibernate-validator
@NotNull private Integer num; public Validator getValidatorFactory() { ValidatorFactory avf = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory(); return avf.getValidator(); } Set<ConstraintViolation<T>> errorSet = getValidatorFactory().validateValue(t, "num",num , true));
ConstraintViolation里面是@NotNull的验证不通过信息,当然验证注解不止这么一个,都可以这样验证
2.spring boot自带Hibernate-validator,要想使用Apache BVal
<!-- 数据验证 Validator bean --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.apache.bval.jsr.ApacheValidationProvider" /> </bean>