bench1ps
bench1ps

Reputation: 183

Cannot @Autowire dependencies in custom Spring validators

I'm trying to validate my Hibernate entities using custom constraints and validators, and some of these validators have dependencies on other services like a configuration class. I understand Spring provides a specific SpringConstraintValidatorFactory precisely for this purpose, and being new at Spring, I found some code to declare the corresponding bean:

The custom validator

@Service
public class MyCustomValidator implements ConstraintValidator<MyConstraint, Integer> {

    @Autowire
    private MyService myService;

    @Override
    public void initialize(MyConstraint constraint) {}

    @Override
    public boolean isValid(Integer someValueToValidate, ConstraintValidatorContext context) { 
        // doStuff 
    }

MyService class

@Service("MyService")
public class MyService {

    private Configuration configuration;

    @PostConstruct
    private void map() throws IOException {
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        InputStream stream = getClass().getClassLoader().getResourceAsStream("config/my_config.yml");
        configuration = objectMapper.readValue(stream, Configuration.class);
    }

    private static class Configuration {
        // some getters and setters
    }
}

Application class

    @Bean
    Validator validator(AutowireCapableBeanFactory autowireCapableBeanFactory) {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
            .configure()
            .constraintValidatorFactory(new SpringConstraintValidatorFactory(autowireCapableBeanFactory))
            .buildValidatorFactory();

        return validatorFactory.getValidator();
    }

Even with this solution, I get a NPE on myService when calling the validator on my entity.

Upvotes: 0

Views: 1492

Answers (1)

Rafal Sujak
Rafal Sujak

Reputation: 21

Hibernate uses own validator so you should override it and use spring validator in hibernate properties using HibernatePropertiesCustomizer.

Here you can find more details: Spring Boot - Hibernate custom constraint doesn't inject Service

Upvotes: 1

Related Questions