springboot~自定义valid及DefaultGroupSequenceProvider的作用

spring一切都可以基于注解来实例,像缓存,校验,字段映射,动态代理等等,今天主要说一下自定义的校验及校验的组关联。

  • 自定义注解,判断name需要以"管理员"结尾
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PrefixAdminValidator.class)
@Documented
public @interface PrefixAdmin {
    String message() default "必须以'角色'结尾";
    //这两个属性必须有
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
@Component
public class PrefixAdminValidator implements ConstraintValidator<PrefixAdmin, String> {

    @Override
    public void initialize(PrefixAdmin constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value.endsWith("角色");
    }
}
  • 然后有个需求,只有字段manager为true时,才进行PrefixAdminValidator的校验,这时我们可以通过DefaultGroupSequenceProvider组依赖来实现
/**
 * 校验的依赖,当isManager为true为,PrefixAdmin注解才有效.
 */
public class RoleProvider implements DefaultGroupSequenceProvider<RoleDTO> {
    @Override
    public List<Class<?>> getValidationGroups(RoleDTO object) {
        List<Class<?>> defaultGroupSequence = new ArrayList<>();

        defaultGroupSequence.add(RoleDTO.class); //注意这里不要写错
        if (object != null && object.isManager()) {
            defaultGroupSequence.add(RoleDTO.CheckManagerGroup.class);
        }
        return defaultGroupSequence;
    }
}
  • 实体在字段上添加对接的注解
@Data
@GroupSequenceProvider(RoleProvider.class)
@ApiModel("角色DTO")
public class RoleDTO {
    private String id;

    @PrefixAdmin(groups = CheckManagerGroup.class)
    private String name;

    private boolean manager;

    public interface CheckManagerGroup {
    }
}
  • 控制器请求体添加@Valid
    @ApiOperation("新增")
	@PostMapping("add")
	@Transactional(rollbackFor = Exception.class)
	public CommonResult add(@Valid @RequestBody RoleDTO roleDTO) {
		if (roleDao.selectOne(new QueryWrapper<Role>().lambda().eq(Role::getName, roleDTO.getName())) != null) {
			return CommonResult.clientFailure(String.format("%s已经存在", roleDTO.getName()));
		}
		Role role = new Role();
		CopyUtils.copyProperties(roleDTO, role);
		roleDao.insert(role);
		updateRolePermissions(roleDTO.getPermissionIdList(), role);
		return CommonResult.ok();
	}
  • 测试数据
  • 结果响应
{
    "code": 400,
    "message": "name必须以'角色'结尾",
    "data": null
}
posted @ 2022-04-27 13:51  张占岭  阅读(734)  评论(0编辑  收藏  举报