本文介紹基于 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
- 以spring boot starter的方式封裝成獨立組件
- 支持正則表達式驗證
最后
感謝大家的閱讀,喜歡的朋友可以在github上點個贊,有任何問題或者建議請在下方留言,期待你的回復。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://juejin.im/post/5af3c25b5188253064651c76