一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專(zhuān)注于服務(wù)器技術(shù)及軟件下載分享
分類(lèi)導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語(yǔ)言|JavaScript|易語(yǔ)言|vb.net|

服務(wù)器之家 - 編程語(yǔ)言 - Java教程 - spring boot+自定義 AOP 實(shí)現(xiàn)全局校驗(yàn)的實(shí)例代碼

spring boot+自定義 AOP 實(shí)現(xiàn)全局校驗(yàn)的實(shí)例代碼

2021-07-30 11:35吃桃子的小松鼠 Java教程

最近公司重構(gòu)項(xiàng)目,重構(gòu)為最熱的微服務(wù)框架 spring boot, 重構(gòu)的時(shí)候遇到幾個(gè)可以統(tǒng)一處理的問(wèn)題。這篇文章主要介紹了spring boot+自定義 AOP 實(shí)現(xiàn)全局校驗(yàn) ,需要的朋友可以參考下

最近公司重構(gòu)項(xiàng)目,重構(gòu)為最熱的微服務(wù)框架 spring boot, 重構(gòu)的時(shí)候遇到幾個(gè)可以統(tǒng)一處理的問(wèn)題,也是項(xiàng)目中經(jīng)常遇到,列如:統(tǒng)一校驗(yàn)參數(shù),統(tǒng)一捕獲異常。。。

僅憑代碼 去控制參數(shù)的校驗(yàn),有時(shí)候是冗余的,但通過(guò)框架支持的 去控制參數(shù)的校驗(yàn),是對(duì)于開(kāi)發(fā)者很友好,先看下面的例子

?
1
2
3
4
@notempty(message="手機(jī)號(hào)不能為空")
  @size(min=11,max=11,message="手機(jī)號(hào)碼長(zhǎng)度不正確")
  @pattern(regexp=stringutils.regexp_mobile,message="手機(jī)號(hào)格式不正確")
 private string mobile;

這是spring boot支持的 校驗(yàn)注解,然后我們?cè)?contoller層 加上@valid 注解 就可以達(dá)到校驗(yàn)的目的。這是一種框架自帶的

本章 就展示一種 自定義的 aop 校驗(yàn),首先 寫(xiě)一個(gè)注解,注解里面可以寫(xiě)上 我們需要校驗(yàn)的規(guī)則, 比如長(zhǎng)度,正則。。。

?
1
2
3
4
5
6
7
8
9
10
11
12
@documented
@target({elementtype.field,elementtype.method})
@retention(retentionpolicy.runtime)
public @interface validateparam {
  int min() default 0;
  int max() default integer.max_value;
  string message() default "params is not null";
  string regexp();
  class<?>[] groups() default { };
   class<? extends payload>[] payload() default { };
   boolean isnotnull() default true;
}

然后定義一個(gè)aop類(lèi)

?
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.onecard.primecard.common.aop;
import java.lang.reflect.field;
import java.lang.reflect.method;
import java.lang.reflect.parameterizedtype;
import java.util.arraylist;
import java.util.arrays;
import java.util.regex.pattern;
import org.aspectj.lang.joinpoint;
import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.annotation.around;
import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.annotation.before;
import org.aspectj.lang.annotation.pointcut;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
import org.springframework.stereotype.component;
import com.jfcf.core.dto.resultdata;
import com.onecard.core.support.util.stringutils;
import com.onecard.primecard.common.annotation.validateparam;
import com.onecard.primecard.common.utils.resultdatautil;
/**
 * 全局 切面類(lèi)(校驗(yàn)參數(shù))
 *
 * @author administrator
 *
 */
@aspect
@component
public class gobalhandleraspect {
  private static logger logger = loggerfactory.getlogger(gobalhandleraspect.class);
  @pointcut("execution(* 包名.controller..*.*(..)) && execution(* 包名.controller..*.*(..))")
  public void checkaspect(){};
  @before("checkaspect()")
  public void befor(joinpoint joinpoint) throws exception{
    //前置統(tǒng)一輸出參數(shù)
    object[] args = joinpoint.getargs();
    if(args != null && args.length>0){
      object obj = args[0];
      parameterizedtype pt = (parameterizedtype)obj.getclass().getgenericsuperclass();
      class<?> classzz = (class<?>) pt.getactualtypearguments()[0];
      logger.info("【小x卡】-【請(qǐng)求實(shí)體入?yún)ⅰ浚?quot;+classzz.newinstance().tostring());
    }
  }
  @around("checkaspect()")
  public object around(proceedingjoinpoint joinpoint) throws throwable{
    //校驗(yàn)參數(shù)
    object[] args = joinpoint.getargs();
    object obj = null;
    if(args != null && args.length > 0){
      obj = args[0];
      class classzz = obj.getclass();
      //沒(méi)有順序和秩序的數(shù)組
      field[] fieldarray = classzz.getdeclaredfields();
      arraylist<field> fieldlist = new arraylist<field>(arrays.aslist(fieldarray));
      string res = checkparam(fieldlist,obj);
      if(stringutils.isnotnull(res)){
        return resultdatautil.result(resultdata.status_param_error, res);
      }
    }
    return joinpoint.proceed();
  }
  private string checkparam(arraylist<field> fieldlist, object obj) throws exception {
    for(field field : fieldlist){
      validateparam validateparam = field.getannotation(validateparam.class);
      logger.info("【小x卡】獲取注解值:"+validateparam.isnotnull()+"min="+validateparam.min()+"max="+validateparam.max());
      method method = obj.getclass().getmethod("get"+getmethodname(field.getname()));
      logger.info("【小x卡】入?yún)?shí)體方法名稱(chēng):"+method.getname());
      if(method != null){
        object val = method.invoke(obj);
        logger.info("【小x卡】回調(diào)方法:"+val);
        if(validateparam != null && validateparam.isnotnull() == true){
          if(null == val || "".equals(val) ){
            return field.getname()+"必填參數(shù)為空";
          }
        }
        if(validateparam.min()==11 && validateparam.max() == 11){
          if(val.tostring().length() != 11){
            return field.getname()+"請(qǐng)輸入?yún)?shù)正確的長(zhǎng)度";
          }
        }
        if(validateparam.regexp().equals(stringutils.regexp_mobile)){
          if(!pattern.matches(stringutils.regexp_mobile, val.tostring())){
            return field.getname()+"參數(shù)格式錯(cuò)誤";
          }
        }
      }
    }
    return null;
  }
   /**
   * 方法首字母大寫(xiě)
   * @param fieldname
   * @return
   */
  private string getmethodname(string fieldname) {
    stringbuffer buffer = new stringbuffer();
    string firstletter = fieldname.substring(0, 1).touppercase();
    return buffer.append(firstletter).append(fieldname.substring(1, fieldname.length())).tostring();
  }   
 }

定義一個(gè)切點(diǎn) @pointcut, 用execution 表達(dá)式,去獲取要校驗(yàn)的 某個(gè)類(lèi) 和某個(gè)方法, 也就是連接點(diǎn),然后 用定義一個(gè)通知,上面代碼中有2個(gè)通知,一個(gè)前置通知@before,一個(gè)環(huán)繞通知@around,我們使用功能最強(qiáng)大的環(huán)繞通知。

通過(guò)上面的代碼可以看出  首先獲取參數(shù),然后通過(guò)反射機(jī)制 獲取 入?yún)?duì)象中的全部字段, 再去獲取 我們?cè)谧侄沃屑?我們自定義注解的字段,通過(guò)反射方法的回調(diào),獲取字段值,對(duì)值做判斷, 返回校驗(yàn)結(jié)果。

總結(jié)

以上所述是小編給大家介紹的spring boot+自定義 aop 實(shí)現(xiàn)全局校驗(yàn)的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!

原文鏈接:https://www.cnblogs.com/dream-sun/p/10677350.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美日韩国产一区二区三区在线观看 | 涩涩屋在线观看 | 大团圆6全文在线阅读 | 肉浦团在线观看 | 日本wwxx护士| 亚洲高清毛片一区二区 | 欧美洲大黑香蕉在线视频 | 日本黄色录像视频 | 波多野结衣之双方调教在线观看 | 久久成人a毛片免费观看网站 | 国产成人啪精品午夜在线播放 | 国产成人福利色视频 | 精品久久香蕉国产线看观看麻豆 | 国产一区二区三区在线观看视频 | 成人欧美一区在线视频在线观看 | 好大用力深一点 | 亚洲国产欧美久久香综合 | 掰开逼操 | 精品9e精品视频在线观看 | 女教师被学生糟蹋三天 | 韩国三级做爰 | 丁香六月婷婷激情 | 乌克兰少妇大胆大BBW | 免费yjsp妖精com | 国产精品青青青高清在线观看 | 日本护士xxxx视频 | 恩爱夫妇交换小说 | 成人免费观看在线视频 | 亚洲老头老太hd | 亚洲精品视频在线 | 国内精品久久久久久久久 | 好男人社区www影院在线观看 | 花房乱爱在线观看 | 波多 在线播放 | 精品久久久久久久高清 | 欧美成人香蕉在线观看 | 特黄特色大片免费高清视频 | 无限资源在线观看高清 | 欧美午夜网站 | 憋尿调教绝望之岛 | 国内精品久久久久久中文字幕 |