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:

1
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
2
3
4
5
6
<!-- 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时,一定要是静态的,别遇上序列化问题

一次技术问答

## 一次技术问答最近一年多都没有写博客了,技术上做了很多有意义的事情,也有一些经验上的积累,逐步沉淀到博客上。今天回答某公司的技术上的一些疑问,把问题和回答贴上来。逐步`养`自己的技术观。### 1. 如何做数据安全防范?还有哪些支付安全需要注意?数据安全防范主要分为两个...… Continue reading

2016年05月Reading Notes

Published on August 10, 2016

2016年05月Reading Notes

Published on June 19, 2016