Spring Boot - Hibernate custom constraint doesn't inject Service

跟風遠走 提交于 2019-11-29 12:17:09
M. Deinum

I would expect that Spring Boot would wire the existing validator to the EntityManager apparently it doesn't.

You can use a HibernatePropertiesCustomizer and add properties to the existing EntityManagerFactoryBuilder and register the Validator.

NOTE: I'm assuming here that you are using Spring Boot 2.0

@Component
public class ValidatorAddingCustomizer implements HibernatePropertiesCustomizer {

    private final ObjectProvider<javax.validation.Validator> provider;

    public ValidatorAddingCustomizer(ObjectProvider<javax.validation.Validator> provider) {
        this.provider=provider;
    }

    public void customize(Map<String, Object> hibernateProperties) {
        Validator validator = provider.getIfUnique();
        if (validator != null) {
            hibernateProperties.put("javax.persistence.validation.factory", validator);
        }
    }
}

Something like this should wire the existing validator with hibernate and with that it will make use of auto wiring.

NOTE: You don't need to use @Component on the validator the autowiring is build into the validator factory before returning the instance of the Validator.

To have the Spring beans injected into your ConstraintValidator, you need a specific ConstraintValidatorFactory which should be passed at the initialization of the ValidatorFactory.

Something along the lines of:

ValidatorFactory validatorFactory = Validation.byDefaultProvider()
    .configure()
    .constraintValidatorFactory( new MySpringAwareConstraintValidatorFactory( mySpringContext ) )
    .build();

with MySpringAwareConstraintValidatorFactory being a ConstraintValidatorFactory that injects the beans inside your ConstraintValidator.

I suspect the ValidatorFactory used by Spring Data does not inject the validators when creating them, which is unfortunate.

I suppose you should be able to override it. Or better, you should open an issue against Spring Boot/Spring Data so that they properly inject the ConstraintValidators as it the second time in a row we have this question on SO.

The answer is quite big to post here. Please check for this article in S.O to help you with. This should help you get started.

Test Custom Validator with Autowired spring Service

The problem is hibernate will no way know spring definition. However you can make Entities to be aware of any type of javax.validation types. Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!