spring @Validated 注解开发中使用group分组校验的实现

spring @Validated 注解开发中使用group分组校验的实现

之前知道spring支持JSR校验,在自己定义的bean中加入@NotNull,@NotBlank,@Length等之类的校验用于处理前台传递过来的request请求,避免在写多余的代码去处理.

但是随着业务的复杂度增加,对于校验的制定也越来越有要求,这个时候就需要引入分组group的概念,在自定义注解@Validated中

spring @Validated 注解开发中使用group分组校验的实现

定义了一个Class[]数组用来分组.这样我们就可以引入分组校验的概念,首先根据需要的分组新建自己的接口.

spring @Validated 注解开发中使用group分组校验的实现

spring @Validated 注解开发中使用group分组校验的实现

然后在需要校验的bean上加入分组:

spring @Validated 注解开发中使用group分组校验的实现

最后根据需要,在Controller处理请求中加入@Validated注解并引入需要校验的分组.

@Validated({Insert.class})AgentContractBean paramBean

整个Spring请求bean的分组校验就算是完成了.

使用Spring @Validated 进行Groups验证是遇到的坑

最近新项目是使用Hibernate Validator做表单验证,遇到有id在更新时不能为空,而在添加时需要为空的情况,所有使用了group属性来指定在什么情况下使用哪个验证规则,而在Controller方法只使用@Validated({Creation.class})来分组验证:

public ApiResponse<UserDTO> createUser(@Validated({Creation.class}) @RequestBody UserDTO userDTO) {
    log.debug("创建用户 : {}", userDTO);
    if (userRepository.findOneByLoginName(userDTO.getLoginName().toLowerCase()).isPresent()) {
      return ApiResponse.ofFailure("用户名已存在");
    } else {
      UserDTO newUser = userService.createUser(userDTO);
      return ApiResponse.ofSuccess(newUser);
    }
  }

但是出现其他字段不执行验证的问题,找了一大圈,发现@Validated在分组验证时并没有添加Default.class的分组,而其他字段默认都是Default分组,所以需要让分组接口继承Default:

public interface Creation extends Default {
}