bval-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Bean Validation > Obtaining a validator
Date Tue, 15 Jun 2010 11:00:00 GMT
Space: Apache Bean Validation (https://cwiki.apache.org/confluence/display/BeanValidation)
Page: Obtaining a validator (https://cwiki.apache.org/confluence/display/BeanValidation/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:

{code:java}
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
{code}

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:

{code:java}
ValidatorFactory avf = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory();
{code}

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:

{code:java}
public enum MyValidatorFactory {
    
    SINGLE_INSTANCE {
    
        ValidatorFactory avf = Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory();
        
        @Override
        public Validator getValidator() {
            return avf.getValidator();
        }
        
    };
    
    public abstract Validator getValidator(); 
}
{code}

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:

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

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

h3. Using Guice

TBD

h3. Using CDI

TBD

Change your notification preferences: https://cwiki.apache.org/confluence/users/viewnotifications.action

Mime
View raw message