我有一个 pojo,这对于多个服务很常见,并且每个服务对该对象都有不同的验证规则。因此,我在我的每个服务中扩展了该 pojo,并覆盖了一些设置器并在那些被覆盖的方法上抛出了约束验证。pojo 是通过 REST 调用从提交的 json 构建的。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) {
似乎验证不适用于杰克逊,因为我看到在其他方法validateParameters
上org.hibernate.validator.internal.engine.ValidatorImpl
调用的方法。
这就是我的ValidationConfiguration
豆子的样子:
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;
}
}
我还对请求参数进行了一些验证,效果很好。但是,它不适用于此设置器。