JSR303

December 02, 2013

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时,一定要是静态的,别遇上序列化问题

2016年05月Reading Notes

## 服务发现服务发现用于动态感知服务提供方地址,并提供服务路由分发策略能力。### 客户端发现客户端从注册中心获取服务列表,客户端监听服务列表的变化,客户端通过路由策略选择合适的服务端地址。服务端在停服务时,需要先通知客户端不要发送新请求过来,等服务端把当前请求处理完后,...… Continue reading

2016年05月Reading Notes

Published on June 19, 2016

2016年05月Reading Notes

Published on May 11, 2016