bval-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
Subject [CONF] Apache Bean Validation > Obtaining a validator
Date Tue, 15 Jun 2010 11:00:00 GMT
Space: Apache Bean Validation (
Page: Obtaining a validator (

Added by Carlos Vara:
To obtain a validator, you must first create a ValidatorFactory. If there is only one jsr303
implementation in your classpath, you can use:

ValidatorFactory vf = Validation.buildDefaultValidatorFactory();

to obtain the factory. If there are various implementations in the classpath, or you want
to be sure you are using the Apache one, you can use:

ValidatorFactory avf = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory();

You should not instantiate more than one factory, as factory creation is a costly process
and the factory also acts as a constraint cache for the validators.

Once you have a ValidatorFactory, obtaining a validator just requires you to call {{ValidatorFactory#getValidator()}}.
The validator implementation is thread-safe, so you can choose to re-use a single instance
of it in all your code or create validators on demand: both options are fine and should perform
equally well.

Below is an example that will create a singleton ValidatorFactory and will let you obtain
validators from it:

public enum MyValidatorFactory {
        ValidatorFactory avf = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory();
        public Validator getValidator() {
            return avf.getValidator();
    public abstract Validator getValidator(); 

Using the above class, obtaining a validator just requires you to call: {{MyValidatorFactory.SINGLE_INSTANCE.getValidator()}}

h3. Using Spring

If you are using Spring, you can easily inject validators in your beans. Simply configure
the factory in your applicationContext by adding:

    <!-- Validator bean -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.apache.bval.jsr303.ApacheValidationProvider"

And Spring will be able to inject Validators and the ValidatorFactory in your beans.

h3. Using Guice


h3. Using CDI


Change your notification preferences:

View raw message