1

我正在使用 Spring Boot 2.2.4.RELEASE,并且我有这个带有自动装配服务的自定义验证器。

@Component
public class CompanyRequiredValidator implements ConstraintValidator<CompanyRequired, Company> {

    @Autowired
    private CompanyService companyService;

    @Override
    public void initialize(CompanyRequired constraintAnnotation) {
    }

    @Override
    public boolean isValid(Company company, ConstraintValidatorContext context) {
        return company != null && companyService.findByCompanyName(company.getCompanyName()) != null;
    }
}

我的验证配置。

@Configuration
public class ValidationConfig {

    @Bean
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public MethodValidationPostProcessor methodValidationProstProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }
}

无论我尝试了什么,自动装配字段都返回 null。我尝试过的事情:

https://medium.com/@ssscripting/getting-autowired-fields-to-work-with-constraintvalidators-in-spring-boot-74424d5b0aaa

Autowired 在自定义约束验证器中给出 Null 值

配置spring验证和hibernate验证

4

0 回答 0