【问题标题】:How to set validation groups dynamically如何动态设置验证组
【发布时间】:2021-08-15 14:49:38
【问题描述】:

我有一个 Spring Boot 应用程序,我想在其中使用 @valid 注释验证请求正文对象。

@PostMapping("update")
public void upateSnippet(@Valid @RequestBody MyDto dto)

这按预期工作。但我需要根据会话特定信息进行验证。所以我创建了应该动态设置的验证组。我不想在控制器中手动调用验证器。验证逻辑应该完全在控制器之外。

所以我要做的是注册一个自定义 MethodValidationInterceptor,我可以在其中指定 determineValidationGroups() 中的组。

public class SessionAwareValidationInterceptor extends MethodValidationInterceptor
{
    @Autowired
    public SessionAwareValidationInterceptor(Validator validator)
    {
        super(validator);
    }

    @Override
    protected Class<?>[] determineValidationGroups(MethodInvocation invocation)
    {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        //return groups from session
    }
}

在我的配置中,我将拦截器注册为任何其他 bean:

@Bean
public MethodValidationInterceptor methodValidationInterceptor(Validator validator)
{
    return new SessionAwareValidationInterceptor(validator);
}

但是我有几个问题:

  1. @Valid 注释独立工作,但 MethodValidationInterceptor 仅在我在控制器类上添加 @Validated 注释时才会调用。
  2. 但即使我同时使用这两个注解,Spring 也不会使用我的自定义拦截器。

如何注册我的自定义MethodValidationInterceptor?或者是否有其他方法可以动态注册验证组?计划 B 将是一些自定义约束验证器,它们可以从会话中获取必要的信息,但我更喜欢组方法。

【问题讨论】:

    标签: java spring-boot validation


    【解决方案1】:

    我知道该怎么做。我必须创建一个自定义 MethodValidationPostProcessor 来返回我的 SessionAwareValidationInterceptor

    public class CustomMethodValidationPostProcessor extends MethodValidationPostProcessor {
        @Override
        @NotNull
        protected Advice createMethodValidationAdvice(Validator validator) {
            return validator != null ? new SessionAwareValidationInterceptor(validator) : new SessionAwareValidationInterceptor();
        }
    }
    

    然后我只是将它注册为bean。这样,我就可以从上面使用我的解决方案。为了让它工作,我必须在类级别使用@Validated注解,在方法参数上使用@Valid注解。

    【讨论】:

      猜你喜欢
      • 2018-04-25
      • 2012-07-14
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多