美文网首页
SpringAOP 实现参数验证

SpringAOP 实现参数验证

作者: 醉疯觞 | 来源:发表于2017-11-24 15:43 被阅读0次

首先

项目集成了 hutool,并结合了网上的一些例子。
作为新手,基于对 Spring Aop 的兴趣,产生了这个项目。
首先 Spring 本身是有 validation 的,但是觉得用起来很麻烦,加之正在学习Aop,所以尝试着自己写了个Aop来实现 validation 的功能,适合新手去了解 AOP 以及 java 反射。
这里是 Spring 的validation
项目地址: 码云github

开始

因为使用 Springboot 所以基于 Springboot
目前设计的是,不符合参数要求直接抛出异常!

@ComponentScan(basePackages = {"team.union"})

首先在Application.java中添加注解扫描一般都是在controller层进行参数验证

@RequestMapping("index")
    @Validate(group={"1"})
    public Object test( TestVo vo) {
        return "ok";
    }

在方法上加上@Validate注解 ,group参数目的是为了VO层分组

public class TestVo {
    @Email
    private String email;

    public String getEmail() {
        return email;
    }

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

再需要验证的地方加入@Email标签既可。

已实现注解

/**
 * 通用正则,regx为正则表达式
 */
@RegxCommon(regx = " ") 
/**
 * 邮箱
 */
@Email

扩展

目前,只写了关于邮箱参数的验证,和正则表达式通用验证,主要是因为懒。 之前设计的时候,考虑到扩展性。
首先自定义注解

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Inherited
@BaseValidate(bean="emailValidator")
public @interface Email {
    String[] group() default {};
}

只要在自定义注解上加入@BaseValidate注解bean参数为验证器的Spring bean名继承team.union.plugin.spring.aop.validate.AbsValidator这个类,实现validate接口,并为该类 加上@Component注解,使其扫描为bean

这是邮箱验证的实现

/** 
     * @Title: validate 
     * @Description: TODO
     * @param  groups validate的group参数
     * @param  annotation 自定义注解obj
     * @param  fieldName 参数名
     * @param  value 参数值
     * @return
     * @throws BaseException   
     */
    @Override
    public boolean validate(String[] groups, Email annotation, String fieldName, Object value) throws BaseException {
        String content = (String) value;
        if (!ReUtil.isMatch(emailRegx, content)) {
            throw new BaseException(ResponseCode.PARAMETER_ILLEGAL.getCode(),
                    String.format("%s %s不是正确的邮箱地址", fieldName, content));
        }
        return true;
    }

相关文章

  • SpringAOP 实现参数验证

    首先 项目集成了 hutool,并结合了网上的一些例子。作为新手,基于对 Spring Aop 的兴趣,产生了这个...

  • springAOP

    springAOP切面拦截参数进行校验。

  • SpringAOP-4

    SpringAOP实现代理-6(注解,组件) 注解的方式实现切面类,并且5种通知方法都可以使用注解完成环绕通知参数...

  • SpringAOP实现

    实现方式一: 引入spring项目必须的AOP包,其次还需要引入aspectjweaver包。定义spring容器...

  • 六、AOP实现自动的系统日志功能

    一、本课目标 掌握SpringAOP的配置 二、使用SpringAOP实现日志输出 在下面的这个示例中,通过Spr...

  • 模型验证方法

    模型验证方法一览 通过交叉验证计算得分 参数: estimator: 实现了'fit'函数的学习器 X: arra...

  • springAOP纯实现

    接口: 实现类: 接口方法实现类的参数 xml配置 测试: 执行结果: 做切面编程aop的时候报java.lang...

  • SpringAOP实现原理

    1. 概述 SpringAOP(Aspect Orient Programming)是一种设计思想,称为面向切面编...

  • java设计模式-代理模式(proxy pattern)

    简述 提到代理模式,脑海中第一个想到的就是springAop。日常工作中,我们用springAop来实现统一权限管...

  • SpringAOP-2

    SpringAOP实现代理-4 ( AOP config形式) 定义切面类 Aspect.java实现一个通知类...

网友评论

      本文标题:SpringAOP 实现参数验证

      本文链接:https://www.haomeiwen.com/subject/qllfbxtx.html