spring的pointcut正则表达式的实现

2022-08-03,,

1.pointcut表达式各部分的约束规则

spring中配置切面或者数据库的事务会要求:对具体方法或者是一类特征相同的方法添加日志,事务,或者其他对原方法的增强。这时候就会用到pointcut表达式对方法进行过滤,筛选出符合要求的方法;

既然会涉及到筛选具体的方法,那pointcut一定要匹配出完整的方法路径:全限定类名+方法名;在同一个类中,方法可能被重写而区分重写的方法就是:参数列表;因此pointcut表达式中必须包含这3部分:全限定类名+方法名+参数列表;在spring中还有:访问修饰符,返回值类型;这2个不是必须的;pointcut整体结构:

有了pointcut的整体结构之后就可以根据自己的规则,分别写这几部分的正则表达式了;

  • execution()这部分是固定写法,它包含了完整的表达式;
  • 访问修饰符,返回值,classpath,methodname之间用空格分开;
  • methodname,paramlist用()分开;methodname(paramlist);

1.1 access_modifier 访问修饰符

访问修饰符有四种取值:public,private,protected,defalut; " * " ,对访问修饰符不加限制;

1.2 return_type 返回值类型

返回值类型可以是任意类型:8个基础类型 + 对象 + 数组 + void;

  • 基础类型的匹配 basic_type: (byte|char|boolean|short|int|long|double|float)
  • 对象匹配:[a-z]\\w*
  • 返回类型可以是以上2种类型的数组(可以是2维,3维,4维.。。);param_type = (basic_type|[a-z]\\w)(\\[\\])**

最后结合返回值:void, * (表示任意类型);返回值的所有可能取值的正则表达式:(void|param_type|\\*)

1.3 class_path 全限定类名

有一个特点:(packagename + “.”) * + classname;包名,类名都可以用同一个正则表达式;

class_path = "((\\*?\\w+\\*?|\\*)\\.)*(\\*?\\w+\\*?|\\*)";

1.4 execution 表达式

  method_name,param_list这2个的匹配分别参照:全限定类名,返回值类型的正则表达式;将这些部分分别写完之后,再按顺序组合一下就可以得到完整的表达式了;再考虑到,写表达式的时候,会习惯性的敲空格,因此可以在合适的地方允许空格;

public class pointcututils {
    private static final string access_modifier = "(public|private|protected|default|\\*)";

    private static final string return_type;

    private static final string class_path = "((\\*?\\w+\\*?|\\*)\\.)*(\\*?\\w+\\*?|\\*)";

    private static final string method_name = "(\\*?\\w+\\*?|\\*)";

    private static final string param_list ;

    private static final string execution ;
    //基础类型
    private static final string basic_type="(byte|char|boolean|short|int|long|double|float)";
    //参数类型
    private static final string param_type;


    static{
        //参数类型:基础类型 + object + 数组类型
        param_type = "("+basic_type+"|[a-z]\\w*)(\\[\\])*";
        //返回值类型:void  + 参数类型
        return_type="(void|"+param_type+"|\\*)";
        //参数列表
        param_list = "(\\.\\.|"+param_type+"(\\s*,\\s*"+param_type+")*" +"|)";
        //execution表达式
        execution = "\\s*execution\\s*\\(\\s*"+access_modifier+"\\s+"+return_type+"\\s+"+class_path+"\\s+"+method_name+"\\(\\s*"+param_list+"\\s*\\)\\s*"+"\\s*\\)\\s*";

    }
	//检测pointcut是否是正确的
    static boolean  checkpointcut(string pointcutreg){
        return pointcutreg == null ? false : pointcutreg.matches(execution);
    }

}

得到的execution表达式可以用来检测pointcut表达式是否写正确;
测试:

        string pointcut = "execution ( default int[][] * rr( .. ) ) ";
        //default访问修饰符,int[][]二维数组 ;
        // * 不限定类名; rr 方法名; .. 任意类型的参数列表;符合定义的规则,预期结果为 true
        boolean correct = pointcututils.checkpointcut(pointcut );
        system.out.println(correct);//结果:true

2.拆分pointcut表达式

拆分流程:

代码:

	//拆分pointcut
    public static pointcut parsepointcut(string pointcut){
        if(!checkpointcut(pointcut))throw new illegalargumentexception("execution grammar format error.");
        string exereg = getbracketstr(pointcut);//获取execution();中括号包裹的部分;
        string paramlist = getbracketstr(exereg).replaceall(" ","");
        int start = exereg.indexof("(");
        exereg = exereg.substring(0,start);
        string[] regs = exereg.split("\\s+");
        string accessmodifier = regs[0];
        string returntype = regs[1];
        string classpath = regs[2];
        string methodname = regs[3];
        return new pointcut(accessmodifier,returntype,classpath,methodname,paramlist);
    }
    static string getbracketstr(string str){
        int start = str.indexof("(");
        int end = str.lastindexof(")");
        return str.substring(start+1,end).trim();
    }

3.过滤

  分别匹配class和method;在拿到pointcut的时候,如何匹配class和method呢?这个时候要对类路径的正则表达式做一下处理;比如:pointcut的classpath部分:

"*weqq*.dgdfgfg.df*"

*weqq*:我们希望能匹配到包名含有 weqq的包;直接使用这个作为正则表达式去匹配类路径肯定是不行的;

 * ====》 重复匹配0次或多次前一个字符或者表达式;
 
如何能达到要求呢?只需要做一下简单处理就好了:*weqq* ====》 \\w*weqq\\w*;将 * 替换成 \\w* 就可以匹配字符了

还有需要注意的是 ".",在正则表达式中表示匹配任意字符;

而我们希望它只是包的分割符,它只表示" . ",而不需要有任何其他的含义,因此需要将 "."转换成普通字符    :  .  ===>   \\.

匹配class的类名

 public static boolean matchclass(pointcut pointcut,class cla){
        if(pointcut.getclasspath().equals("*"))return true;
        return cla.gettypename().matches(pointcut.getclasspath().replaceall("\\*","\\\\w*").replaceall("\\.","\\\\."));
    }


匹配方法:访问修饰符,返回值,方法名,参数列表

   public static boolean matchmethod(pointcut pointcut, method method){
       return matchmodifier(pointcut.getaccessmodifier(),method) &&
              matchreturntype(pointcut.getreturntype(),method) &&
              matchmethodname(pointcut.getmethodname(),method) &&
              matchparamlist(pointcut.getparamlist(),method);


   }

   static boolean matchmodifier(string modifier,method method){
       int modifiers = method.getmodifiers();
        switch (modifier){
            case "default"  :return method.isdefault();
            case "public"   :return modifier.ispublic(modifiers);
            case "private"  :return modifier.isprivate(modifiers);
            case "protected":return modifier.isprotected(modifiers);
            case "*"        :return true;
            default:
                return false;
        }
   }

   static boolean matchreturntype(string returntype,method method){
        if(returntype.equals("*"))return true;
       return returntype.equals(method.getreturntype().getsimplename());
   }

   static boolean matchmethodname(string name,method method){
        if(name.equals("*"))return true;
        return method.getname().matches(name.replaceall("\\*","\\\\w*"));
   }

   static boolean matchparamlist(string paramlist,method method){

        if(paramlist.equals(".."))return true;

       class<?>[] parametertypes = method.getparametertypes();
       if((paramlist.equals("")) ){
           if( parametertypes.length == 0 )return true;
           else return false;
       }
       stringbuilder methodparamlist = new stringbuilder();
       for (class<?> parametertype : parametertypes) {
           methodparamlist.append(","+parametertype.getsimplename());
       }
        string methodparam =  methodparamlist.tostring().substring(1);
        return methodparam.equals(paramlist);

   }

同时匹配上类和方法,就可以对方法增强了;其实可以看到在实现pointcut表达式只用到了少量的正则表达式的知识;execution整体拼凑起来有点多,但是分开来看每部分还是简单的;只需要了解简单的正则和反射,就可以自定义一个pointcut过滤器了。有了这个之后,就可以自己定义实现选择性aop了;

到此这篇关于spring的pointcut正则表达式的实现的文章就介绍到这了,更多相关spring pointcut正则表达式内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《spring的pointcut正则表达式的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。