Running Hibernate Validator in the JBoss Fuse

Solution Verified - Updated -

Environment

  • JBoss Fuse 6.0

Issue

I try to run Hibernate Validator [1] in the OSGi environment. When I attempt to create the Validator instance I see the following message:

Add a provider like Hibernate Validator (RI) to your classpath.
javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider
could be found. Add a provider like Hibernate Validator (RI) to your classpath.
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:271)
at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:110)

[1] http://hibernate.org/validator

Resolution

Default Hibernate ValidatorFactory is not OSGi-friendly. In order to successfully run the Hibernate Validator in the OSGi environment you need to use a custom ValidationProviderResolver explicitly returning the HibernateValidator instance. The snippet below demonstrates such configuration.

public class HibernateValidationProviderResolver implements ValidationProviderResolver {

  @Override
  public List getValidationProviders() {
    return singletonList(new HibernateValidator());
  }

}

The snippet below demonstrates how to wire the custom ValidationProviderResolver into the ValidatorFactory.

Configuration<?> configuration = Validation.byDefaultProvider().providerResolver(
    new HibernateValidationProviderResolver()
).configure();
ValidatorFactory factory = configuration.buildValidatorFactory();
Validator validator = factory.getValidator();

Attachments

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Comments