fix(WebMvcConfig.java): 自定义校验器默认使用ConstraintValidatorFactoryImpl无法注入bean的问题修复

This commit is contained in:
郝先瑞 2022-07-10 14:47:33 +08:00
parent c724696737
commit 9d05d272ab

View File

@ -6,11 +6,12 @@ import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator; import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter; import org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.validation.Validation; import javax.validation.Validation;
@ -43,17 +44,13 @@ public class WebMvcConfig implements WebMvcConfigurer {
} }
@Bean @Bean
public Validator validator() { public Validator validator(final AutowireCapableBeanFactory autowireCapableBeanFactory) {
ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure() ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
.configure()
.failFast(true) // failFast=true 不校验所有参数只要出现校验失败情况直接返回不再进行后续参数校验 .failFast(true) // failFast=true 不校验所有参数只要出现校验失败情况直接返回不再进行后续参数校验
.constraintValidatorFactory(new SpringConstraintValidatorFactory(autowireCapableBeanFactory))
.buildValidatorFactory(); .buildValidatorFactory();
return validatorFactory.getValidator(); return validatorFactory.getValidator();
} }
@Override
public org.springframework.validation.Validator getValidator() {
return new SpringValidatorAdapter(validator());
}
} }