返回顶部

收藏

使用jsr validation动态代理验证java bean

更多

新建项目, 在pom文件中添加如下maven依赖

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator-annotation-processor</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

如下是使用validation验证bean的使用示例:

package cn.outofmemory.hello;

import org.hibernate.validator.constraints.Email;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;

/**
 * Created by outofmemory.cn on 2016/6/28.
 */
public class HelloValidator {
    public static class Student {
        private int id;
        @NotNull
        @Size(max = 20, min=2, message = "student name length must between 2 to 20")
        private String name;

        @NotNull
        @Email
        private String email;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }

    public static void main(String[] args) {
        Student student = new Student();
        student.setName("a");
        student.setEmail("ah");
//
//        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
//        Validator validator = validatorFactory.getValidator();
//        Set<ConstraintViolation<Student>>  violations = validator.validate(student);
//        for (ConstraintViolation<Student> violation : violations) {
//            System.out.println(violation.getMessage());
//        }

        AService aService = (AService) Proxy.newProxyInstance(
                HelloValidator.class.getClassLoader(),
                new Class[]{AService.class},
                new ValidationInvocationHandler(new AServiceImpl())
                );

        aService.processStudent(student);

    }

    public interface AService {
        void processStudent(@Valid Student student);
    }

    public static class AServiceImpl implements  AService{
        public void processStudent(Student student) {
            System.out.println("do something");
        }
    }

    public static class ValidationInvocationHandler implements InvocationHandler {
        static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        final Object proxyTarget;
        public ValidationInvocationHandler(final Object target) {
            proxyTarget = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Annotation[][] annotations = method.getParameterAnnotations();
            for (int parameterIndex = 0; parameterIndex < args.length; parameterIndex++) {
                Annotation[] parameterAnnotations = annotations[parameterIndex];
                for(Annotation parameterAnnotation : parameterAnnotations) {
                    if (parameterAnnotation.annotationType().isAssignableFrom(Valid.class)) {
                        //we need validate this parameter
                        Object parameter = args[parameterIndex];
                        Set<ConstraintViolation<Object>>  violations = validator.validate(parameter);
                        if (violations.size() > 0) {
                            for (ConstraintViolation<Object> violation : violations) {
                                System.out.println(violation.getMessage());
                            }
                        }
                    }
                }
            }
            return method.invoke(proxyTarget, args);
        }
    }

}

标签:java

收藏

0人收藏

支持

1

反对

0

相关聚客文章
  1. liuchi1993 发表 2017-04-03 22:43:26 Java学习路线图
  2. 博主 发表 2017-04-03 16:04:00 内核参数设置错误导致 JVM 无法申请大块内存
  3. 博主 发表 2017-04-02 11:17:05 jdk8_cannot_access_class_file
  4. 方 腾飞 发表 2017-04-02 03:40:54 《Flink官方文档》翻译邀请
  5. liuchi1993 发表 2017-04-01 23:00:57 Java Web 学习路线
  6. liuchi1993 发表 2017-03-31 22:52:10 一文让你明白Java字节码
  7. 大象会跳舞 发表 2017-03-30 20:44:37 Apache Spark 内存管理详解
  8. 信海龙 发表 2017-03-30 03:38:12 Java泛型使用示例整理
  9. lijunshu 发表 2017-03-30 14:48:37 《Netty官方文档》基准测试
  10. 小村长 发表 2017-03-30 14:52:12 Spark Release 2.0.0
  11. zhu329599788@126 发表 2017-03-30 06:15:53 Java基本数据类型总结
  12. 邓龙华 发表 2017-03-30 12:46:20 微软Azure Service Fabric朝开源迈出了第一步

发表评论