时间:2022-06-06 09:33:05 | 栏目:JAVA代码 | 点击:次
项目中写逻辑时,为保证程序的健壮性,需要对各种参数进行判断,这就导致业务代码不只健壮,还十分臃肿。其实 SpringBoot 中已经提供了 Validation 参数验证框架,可以方便的对参数进行合法性校验。
Validation 是用于检查程序代码中参数的有效性的框架,作为 Spring 框架中的一个参数校验工具,集成在 spring-context 包中。
Validation 包含了众多的注解来帮助对Java程序不同类型的参数进行校验,校验相关注解分布在spring-boot-starter-validation 依赖的 javax.validation.constraints 包中。
其他类似注解的使用可以查看javax.validation.constraints 包中定义注解信息。
在实际使用 Validation 框架时,经常会对 @valid 和 @validated 注解的使用产生误解,在这里对比一下两个注解的异同。
在注解的使用上,@Validated 注解可以用于类型、方法和参数上;而 @Valid 还可以用于属性之上。
//@Validated定义
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Validated {
Class<?>[] value() default {};
}
//@Valid定义
@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
public @interface Valid {
}
SpringBoot 中使用 Validator 无需单独引入,因为在 web 依赖包中已经存在,直接使用即可。
<!-- starter web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
如果 SpringBoot 版本比较新,在 web 包中可能已不再包含 Validation 框架,本地使用SpringBoot 2.6.3 版本 web 依赖包已经不再包含。

或者
SpringBoot新版本虽然不在web包中包含,但也提供了start启动依赖提供相关功能,单独引入 Jar 包可以使用如下坐标信息:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
另外,引入依赖时还可以引入 hibernate 提供的 validator框架包,不过使用时需要表明版本号信息。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.5.Final</version>
</dependency>
后端接收请求参数时,通常是使用 JavaBean 对象来接收参数信息,如果想要对实体类中的属性进行校验,则需要对属性使用校验相关的注解标注,并且实体对象必须定义 getter/setter方法,可以使用 lombok 的 @Data。
@Data
public class Customer{
private Long id;
@NotNull
private String countryName;
@NotNull
private String countryCode;
@Email
private String email;
@Valid
private Customer parentCustomerInfo;
}
服务接口接收单个简单参数时,可以在方法参数中直接使用校验注解。
@PostMapping("/get")
public ResultMap getCustomerInfo(@RequestParam("customerCode") @NotNull(message = "用户编码不可以为空!") String customerCode){
return ResultMapUtils().ok();
}
单参数校验时,还需要在 controller 层控制器类中使用 @Validated 标注才会生效。
在实体类中使用校验注解标注需要校验的字段后,还需要在请求层接收参数时开启参数校验,只需要在 controller 接口层的参数中使用 @Validated 标注,在接口接收到请求参数时会自动进行校验。
@Autowired
private CustomerService customerService;
@PostMapping("/execute")
public ResultMap execute(@RequestBody @Validated GeneralDataRequest<CustomerRequest> generalDataRequest){
CustomerRequest request = generalDataRequest.getData();
return customerService.execute(request);
}
使用 Validation 校验异常后,当参数发生异常时,会抛出 MethodArgumentNotValidException 类型的异常,为了程序报错更通俗易懂,可以定义全局异常来捕获该类型的异常,并统一返回结果信息。
@SLF4j
@ControllerAdvice
public class ExceptionConfig {
/**
* 参数校验异常
*/
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResultMap argumentExceptionHandler(MethodArgumentNotValidException exception) {
String message = exception.getBindingResult().getFieldError().getDefaultMessage();
log.info("发生参数异常:{}", message);
return ResultMapUtils.resultError(ErrorCodeConstant.System.E100003, null, message);
}
}