Spring Boot实现通用的接口参数校验

2025-05-29 0 89

本文介绍基于 spring boot 和 jdk8 编写一个 aop ,结合自定义注解实现通用的接口参数校验

缘由

目前参数校验常用的方法是在实体类上添加注解,但对于不同的方法,所应用的校验规则也是不一样的,例如有一个 accountvo 实体:

?

1

2

3

4
public class accountvo {

private string name; // 姓名

private integer age; // 年龄

}

假设存在这样一个业务:用户注册时需要填写姓名和年龄,用户登陆时只需要填写姓名就可以了。那么把校验规则加在实体类上显然就不合适了。

所以一直想实现一种方法级别的参数校验,对于同一个实体参数,不同的方法可以应用不同的校验规则,由此便诞生了这个工具,而且在日常工作中使用了很久。

介绍

先来看看使用的方式:

?

1

2

3

4

5

6

7

8

9

10
@service

public class testimpl implements itestservice {

@override

@check({"name", "age"})

public void testvalid(accountvo vo) {

// ...

}

}

其中方法上的 @check 注解指明了参数 accountvo 中的 name 、 age 属性不能为空。除了非空校验外,还支持大小判断、是否等于等校验

?

1
@check({"id>=8", "name!=aaa", "title<10"})

默认的错误信息会返回字段,错误原因和调用的方法,例如:

?

1

2

3
updateuserid must not null while calling testvalid

id must >= 8 while calling testvalid

name must != aaa while calling testvalid

也支持自定义错误返回信息:

?

1

2

3

4
@check({"title<=8:标题字数不超过8个字,含标点符号"})

public void testvalid(testpo po) {

// ...

}

只需要在校验规则后加上 : ,后面写上自定义信息,就会替换默认的错误信息。

ps: 核心原理是通过反射获取参数实体中的字段的值,然后根据规则进行校验, 所以目前只支持含有一个参数的方法,并且参数不能是基础类型。

使用

spring-boot 中如何使用 aop 这里不再赘述,主要介绍 aop 中的核心代码。

maven 依赖

除了 spring-boot 依赖之外,需要的第三方依赖,不是核心的依赖,可以根据个人习惯取舍:

?

1

2

3

4

5

6

7

8

9

10

11

12

13
<!-- 用于字符串校验 -->

<dependency>

<groupid>org.apache.commons</groupid>

<artifactid>commons-lang3</artifactid>

<version>3.3.2</version>

</dependency>

<!-- 用于日志打印 -->

<dependency>

<groupid>org.slf4j</groupid>

<artifactid>slf4j-api</artifactid>

<version>1.7.25</version>

</dependency>

自定义注解

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
import java.lang.annotation.elementtype;

import java.lang.annotation.retention;

import java.lang.annotation.target;

import static java.lang.annotation.retentionpolicy.runtime;

/**

* 参数校验 注解

* created by cipher on 2017/9/20.

*/

@target({elementtype.type, elementtype.method})

@retention(runtime)

public @interface check {

// 字段校验规则,格式:字段名+校验规则+冒号+错误信息,例如:id<10:id必须少于10

string[] value();

}

核心代码

通过切面拦截加上了 @check 注解的接口方法,在方法执行前,执行参数校验,如果存在错误信息,则直接返回:

?

1

2

3

4

5

6

7

8

9

10

11

12
@around(value = "@com.cipher.checker.check") // 这里要换成自定义注解的路径

public object check(proceedingjoinpoint point) throws throwable {

object obj;

// 参数校验

string msg = docheck(point);

if (!stringutils.isempty(msg)) {

// 这里可以返回自己封装的返回类

throw new illegalargumentexception(msg);

}

obj = point.proceed();

return obj;

}

核心的校验方法在 docheck 方法中,主要原理是获取注解上指定的字段名称和校验规则,通过反射获取参数实体中对应的字段的值,再进行校验

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33
/**

* 参数校验

*

* @param point proceedingjoinpoint

* @return 错误信息

*/

private string docheck(proceedingjoinpoint point) {

// 获取方法参数值

object[] arguments = point.getargs();

// 获取方法

method method = getmethod(point);

string methodinfo = stringutils.isempty(method.getname()) ? "" : " while calling " + method.getname();

string msg = "";

if (ischeck(method, arguments)) {

check annotation = method.getannotation(check.class);

string[] fields = annotation.value();

object vo = arguments[0];

if (vo == null) {

msg = "param can not be null";

} else {

for (string field : fields) {

// 解析字段

fieldinfo info = resolvefield(field, methodinfo);

// 获取字段的值

object value = reflectionutil.invokegetter(vo, info.field);

// 执行校验规则

boolean isvalid = info.optenum.fun.apply(value, info.operatornum);

msg = isvalid ? msg : info.innermsg;

}

}

}

return msg;

}

可以看到主要的逻辑是:

解析字段 -> 获取字段的值 -> 执行校验规则

内部维护一个枚举类,相关的校验操作都在里面指定:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37
/**

* 操作枚举

*/

enum operator {

/**

* 大于

*/

greater_than(">", checkparamaspect::isgreaterthan),

/**

* 大于等于

*/

greater_than_equal(">=", checkparamaspect::isgreaterthanequal),

/**

* 小于

*/

less_than("<", checkparamaspect::islessthan),

/**

* 小于等于

*/

less_than_equal("<=", checkparamaspect::islessthanequal),

/**

* 不等于

*/

not_equal("!=", checkparamaspect::isnotequal),

/**

* 不为空

*/

not_null("not null", checkparamaspect::isnotnull);

private string value;

private bifunction<object, string, boolean> fun;

operator(string value, bifunction<object, string, boolean> fun) {

this.value = value;

this.fun = fun;

}

}

由于篇幅原因,这里就不一一展开所有的代码,有兴趣的朋友可以到以下地址获取所有的源码:ciphermagic/java-learn/sandbox/checker

todo

  1. 以spring boot starter的方式封装成独立组件
  2. 支持正则表达式验证

最后

感谢大家的阅读,喜欢的朋友可以在github上点个赞,有任何问题或者建议请在下方留言,期待你的回复。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://juejin.im/post/5af3c25b5188253064651c76

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring Boot实现通用的接口参数校验 https://www.kuaiidc.com/112001.html

相关文章

发表评论
暂无评论