spring boot 中使用 Hibernate validate 进行入参字段校验,一般用于web 接口入参校验,用起来非常方便。
spring boot 的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import org.hibernate.validator.HibernateValidator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory;
@Configuration public class ValidatorConfiguration {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() { MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor(); postProcessor.setValidator(validator()); return postProcessor; }
@Bean public Validator validator(){ ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class ) .configure() .addProperty( "hibernate.validator.fail_fast", "true" ) .buildValidatorFactory(); Validator validator = validatorFactory.getValidator(); return validator; } }
|
controller 中使用
使用步骤:
- 在 controller 类上 @Validated
- BindingResult result 这个不能省,必须要有,测试不加不行。
- @Valid 加上这个注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Validated public class NewsInfoController {
@RequestMapping(value = "/save" ,method={RequestMethod.POST,RequestMethod.GET}) @ResponseBody public ResultVo saveNewsInfo(@RequestBody @Valid NewsRequestVo newsRequestVo, BindingResult result){ ResultVo resultVo = new ResultVo(); newsInfoBusiness.insert(newsRequestVo); return resultVo; }
|
实体类中使用
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class NewsInfo implements Serializable { private static final long serialVersionUID = 3148176768559230877L;
private String id; private String newsNo; @NotNull @Length(max=30, message="长度超过限制") private String title; }
|