概述
Bean Validation源于JSR-303 ,而JSR303是 Java EE 6 中的一项子规范。JSR349、JSR380是其升级版,添加了一些新的特性。Oracle公司传统艺能,一流公司定标准,它们只定义了一些校验注解(Constraint),如@Null@NotNull@Pattern],位于javax.validation.constraints包下,只提供规范不提供实现。Hibernate Validator是对这个规范的实现(不要和数据库ORM框架Hibernate联系在一起),并增加了一些自定义校验注解,如@Email、@Length、@Range,位于org.hibernate.validator.constraints包下。这里贴上常用的注解和解释
引入依赖
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>6.0.1.Final</version></dependency>
新增配置类
- HibernateValidationConfig.java
java">package com.example.learn.config;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 HibernateValidationConfig {@Beanpublic MethodValidationPostProcessor methodValidationPostProcessor() {/**默认是普通模式,会返回所有的验证不通过信息集合*/MethodValidationPostProcessor processor = new MethodValidationPostProcessor();/**设置validator模式为快速失败返回*/processor.setValidator(validator());return processor;}@Beanpublic Validator validator() {ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory();Validator validator = validatorFactory.getValidator();return validator;}}
用法与测试
- ValidateTestController.java
java">package com.example.learn.controller;import com.example.learn.common.returns.CommonResult;
import com.example.learn.pojo.dto.UserDTO;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;import javax.validation.constraints.Min;@RestController
@RequestMapping(value = "/validate/test")
@Validated
public class ValidateTestController {@PostMapping(value = "/save")public CommonResult saveUser(@RequestBody @Validated UserDTO userDTO) {System.out.println(userDTO.toString());return CommonResult.success();}@GetMapping(value = "/{userId}")public CommonResult detail(@PathVariable("userId") @Min(value = 200L,message = "userId须大于200") Long userId) {return CommonResult.success();}@GetMapping(value = "/getByAccount")public CommonResult getUser(@RequestParam(value = "account") @Length(min = 6, max = 20, message = "account的长度须介于6和20之间") String account) {return CommonResult.success();}
}
- UserDTO.java
java">package com.example.learn.pojo.dto;import lombok.Data;
import org.hibernate.validator.constraints.Length;import javax.validation.constraints.NotNull;
import java.math.BigDecimal;@Data
public class UserDTO {private Long userId;@NotNull(message = "用户名不能为空")@Length(min = 2, max = 10, message = "用户名称需要在2和10之间")private String userName;@NotNull(message = "账户不能为空")@Length(min = 6, max = 20, message = "账户长度需要在6和20之间")private String account;@NotNull(message = "密码不能为空")@Length(min = 7,max = 20, message = "密码长度需要在7和20之间")private String password;@NotNull(message = "金额不能为空")private BigDecimal money;
}
参考
RuoYi-Vue-v3.8.9
【SpringBoot】使用hibernate-validator实现优雅的参数校验