Hibernate Validator 不验证用约束注释注释的方法参数

Hibernate Validator doesn't validate method parameters annotated with constraint annotations

我有一个 pojo,它在多个服务中很常见,并且每个服务对该对象都有不同的验证规则。因此,我在我的每个服务中扩展了该 pojo 并覆盖了一些 setter 并对那些覆盖的方法进行了约束验证。 pojo 是根据提交的 json 通过 REST 调用构建的。 Jackson 是应该调用 setter.

的库
    @JsonSetter("name")
    public void setName(@Length(min = 1, max = 50) @NotBlank String name) {
        this.name = name;
    }

这是我的 REST 方法声明:

public ResponseEntity<?> createEntity(@Valid @RequestBody EntityDTO entity) {

我看到 org.hibernate.validator.internal.engine.ValidatorImplorg.hibernate.validator.internal.engine.ValidatorImpl 方法在其他方法上调用时,似乎验证不适用于 Jackson。

我的 ValidationConfiguration bean 是这样的:

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validator;

@Configuration
public class ValidationConfiguration {
    public ValidationConfiguration() {
    }

    @Bean(name = "overriddenValidator")
    public Validator validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setParameterNameDiscoverer(new CustomParameterNameDiscoverer());
        MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
        factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
        return factoryBean;
    }


    @Bean
    public static MethodValidationPostProcessor methodValidationPostProcessor(Environment environment, @Qualifier("overriddenValidator") Validator validator) {
        validator.forExecutables();
        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;
    }
}

我也对请求参数做了一些验证,效果很好。但是,它不适用于此 setter.

我无法让它在 setter 上运行,但是,奇怪的是,验证开始在 getter 上运行。即使没有显式调用 getter。好像跟杰克逊有关??

    @Override
    @Length(min = 1, max = 50)
    @NotBlank
    public String getName() {
        return super.getName();
    }