Spring Boot 中非 rest 方法的 DTO 约束验证

Constraint validations of DTOs for non-rest methods in SpringBoot

我在用 @PostMaping, @PutMapping 注释的 REST 调用上对 DTO 使用 javax + Hibernate 验证。它确实工作得很好,但我也有一个地方,我将 2 个对象合并到一个 DTO,然后我将它传递到 "Manager" 层,我很想给 @Valid 注释争论,我期待它工作,但不幸的是,验证没有启动。 有没有办法强迫它?

======================更新====================

我的 class 确实在顶部有 @Validated 注释。 应验证参数的方法是 public.

我配置了以下 bean:

    @Bean
    public static LocalValidatorFactoryBean defaultValidator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
        factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
        return factoryBean;
    }

    @Bean
    public static MethodValidationPostProcessor methodValidationPostProcessor(Environment environment, Validator validator) {
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
        boolean proxyTargetClass = (Boolean)environment.getProperty("spring.aop.proxy-target-class", Boolean.class, true);
        processor.setProxyTargetClass(proxyTargetClass);
        processor.setValidator(validator);
        return processor;
    }



该注释不适用于 @RestController class 方法,但 @RequestMapping 除外,因此我创建了一个虚拟验证器,如下所示:

@Service
@Validated
@Slf4j
public class DTOValidator {

    /**
     * This method triggers DTO validation same way as Spring REST layer does for @RequestMapping method argument.
     */
    public void validate(@Valid DTO dto) {
        log.trace("dto passed the validation = {}", dto);
    }

}