JSR303

how to obtain a validator

To obtain a Validator, you must first create a ValidatorFactory. If there is only one Bean Validation implementation in your classpath, you can use:

ValidatorFactory vf = Validation.buildDefaultValidatorFactory();

You should usually not instantiate more than one factory; factory creation is a costly process. Also, the factory also acts as a cache for the available validation constraints.

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

public enum MyValidatorFactory {
    SINGLE_INSTANCE {
        ValidatorFactory avf =
            Validation.byProvider(ApacheValidationProvider.class).configure().buildValidatorFactory();
        @Override
        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()

Using The Spring Framework

If you are using Spring, you can easily inject Validators into 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" />
</bean>

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

comment:

这里使用的是apache bval,
一般使用hibernate的实现.

在javabean中使用validator时,一定要是静态的,别遇上序列化问题

给攻城狮一个小小的鼓励!