Configuration and ValidatorFactory
5.1. Configuration and ValidatorFactory There are three different methods in the Validation class to create a Validator instance. The easiest in shown in Example 5.1, “Validation.buildDefaultValidatorFactory()”. Example 5.1. Validation.buildDefaultValidatorFactory() ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); You can also use the method Validation.byDefaultProvider() which will allow you to configure several aspects of the created Validator instance: Example 5.2. Validation.byDefaultProvider() Configuration config = Validation.byDefaultProvider().configure(); config.messageInterpolator(new MyMessageInterpolator()) .traversableResolver( new MyTraversableResolver()) .constraintValidatorFactory(new MyConstraintValidatorFactory()); ValidatorFactory factory = config.buildValidatorFactory(); Validator validator = factory.getValidator(); We will learn more about MessageInterpolator, TraversableResolver and ConstraintValidatorFactory in the following sections. Last but not least you can ask for a Configuration object of a specific Bean Validation provider. This is useful if you have more than one Bean Validation provider in your classpath. In this situation you can make an explicit choice about which implementation to use. In the case of Hibernate Validator the Validator creation looks like: Example 5.3. Validation.byProvider( HibernateValidator.class ) HibernateValidatorConfiguration config = Validation.byProvider( HibernateValidator.class ).configure(); config.messageInterpolator(new MyMessageInterpolator()) .traversableResolver( new MyTraversableResolver()) .constraintValidatorFactory(new MyConstraintValidatorFactory()); ValidatorFactory factory = config.buildValidatorFactory(); Validator validator = factory.getValidator(); Tip The generated Validator instance is thread safe and can be cached.