Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Custom javax.validation.Validator in BeanValidator #4481

Open
tobiaskahl opened this issue Aug 3, 2018 · 1 comment
Open

Allow Custom javax.validation.Validator in BeanValidator #4481

tobiaskahl opened this issue Aug 3, 2018 · 1 comment

Comments

@tobiaskahl
Copy link

Actually there are 2 Methods in com.vaadin.flow.data.validator.BeanValidator which return the JavaxBeanValidationFactory und Validator.

protected static ValidatorFactory getJavaxBeanValidatorFactory() {
    return LazyFactoryInitializer.FACTORY;
}

public javax.validation.Validator getJavaxBeanValidator() {
    return getJavaxBeanValidatorFactory().getValidator();
}

I would like to set the ValidatorFactory from outside of the BeanValidator to use custom Validator-Implementations. e.g. Springs org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.

@kaliuzhnyi
Copy link

kaliuzhnyi commented Sep 10, 2023

Hey. I found a hard way and it's not good, but it's work.
The code is for JAVA 12+ and Vaadin 24

@Configuration
public class ValidatorConfig implements InitializingBean {

    @Autowired
    private ValidatorFactory validatorFactory;

    @Bean
    public ValidatorFactory validatorFactory(MessageSource messageSource) {
        var bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource);
        return bean;
    }

    @Bean
    public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(ValidatorFactory validatorFactory) {
        // AvailableSettings.JPA_VALIDATION_FACTORY -> javax.persistence.validation.factory
        // AvailableSettings.JAKARTA_VALIDATION_FACTORY -> jakarta.persistence.validation.factory
        return hibernateProperties ->
            hibernateProperties.put(AvailableSettings.JAKARTA_VALIDATION_FACTORY, validatorFactory);
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        var className = "com.vaadin.flow.data.validator.BeanValidator.LazyFactoryInitializer";
        var fieldName = "FACTORY";
        var field = FieldUtils.getDeclaredField(ClassUtils.getClass(className), fieldName, true);

        var unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        var unsafe = (Unsafe) unsafeField.get(null);

        unsafe.putObject(unsafe.staticFieldBase(field),
                unsafe.staticFieldOffset(field),
                validatorFactory);

    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants