AOP 框架:Aspectj(不依赖 Spring)

官网下载

Aspectj 官网地址 Aspectj 官网下载
下载后的aspectj-1.9.6.jar是一个可执行文件,直接双击打开,安装:

然后配置到idea中即可在执行时使用

示例

https://gitee.com/sunshine_2016/demos/tree/master/aspectj-demo

Aspectj有两种形式:

  1. 如果是对项目中的代码进行切片,直接使用注解
  2. 如果是对项目的三方依赖中的代码进行增强,需要编写.aj文件(直接用注解方式没有生效,不确定是不是我配置错了)
package demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

public class HelloWorld {

    private static final Logger logger = LoggerFactory.getLogger(HelloWorld.class);

    public void say() {
        logger.info("HelloWorld");
    }

    public void say(String message) {
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("Hello{}", message);
    }
}

注解 Demo

package demo.aspectj;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class HelloWorldAspect {

    @Pointcut("execution(* demo.HelloWorld.say(..))")
    public void cutSay() {

    }

    // 实现:打印切片方法的执行耗时
    @Around("cutSay()")
    public Object aroundSay(ProceedingJoinPoint joinPoint) {
        try {
            long start = System.currentTimeMillis();
            Object proceed = joinPoint.proceed();
            System.out.println(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + ",耗时:" + (System.currentTimeMillis() - start) + "ms");
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    // 实现:方法执行完毕后,打印空行
    @After("cutSay()")
    public void afterSay() {
        // 实现方法执行完毕打印一个空行
        System.out.println();
    }
}
  1. @Aspect
  2. @Pointcut
  3. @Around
  4. @After
  5. @AfterThrowing

.aj Demo

package demo.aspectj;

public aspect LoggerAspect {

    pointcut cutInfo(): call(void org.slf4j.Logger.info(..));

    before(): cutInfo() {
    }

    // 获取切片方法的参数
    void around(): cutInfo() {
        proceed();
        Object[] args = thisJoinPoint.getArgs();
        String s = String.valueOf(args[0]);
        for (int i = 1; i < args.length; i++) {
            s = s.replace("{}", String.valueOf(args[i]));
        }
        System.out.println("打印INFO级别日志:" + s);
    }
}

关键字

  1. aspect
  2. pointcut
  3. before
  4. around
  5. after

内置?方法

  1. call()
  2. args()
  3. target()
  4. proceed()

内置?属性

  1. thisJoinPoint
  2. thisJoinPointStaticPart
  3. thisEnclosingJoinPointStaticPart

切入点表达式终结篇

原文:https://blog.ityoung.tech/?p=836

切入点表达式概念及作用

概念:
    指的是遵循特定的语法用于捕获每一个种类的可使用连接点的语法。 
作用:
    用于对符合语法格式的连接点进行增强。 

按照用途分类

主要的种类: 
    方法执行:(MethodSignature)
    方法调用:(MethodSignature)
    构造器执行:(ConstructorSignature)
    构造器调用:(ConstructorSignature)
    类初始化:(TypeSignature)
    属性读操作:(FieldSignature)
    属性写操作:(FieldSignature)
    例外处理执行:(TypeSignature)
    对象初始化:(ConstructorSignature)
    对象预先初始化:(ConstructorSignature)+

切入点表达式的关键字

支持的AspectJ切入点指示符如下: 
    execution:用于匹配方法执行的连接点; 
    within:用于匹配指定类型内的方法执行; 
    this:用于匹配当前AOP代理对象类型的执行方法;注意是AOP代理对象的类型匹配,这 样就可能包括引入接口也类型匹配; 
    target:用于匹配当前目标对象类型的执行方法;注意是目标对象的类型匹配,这样就 不包括引入接口也类型匹配; 
    args:用于匹配当前执行的方法传入的参数为指定类型的执行方法; @within:用于匹配所以持有指定注解类型内的方法; 
    @target:用于匹配当前目标对象类型的执行方法,其中目标对象持有指定的注解; 
    @args:用于匹配当前执行的方法传入的参数持有指定注解的执行; 
    @annotation:用于匹配当前执行方法持有指定注解的方法; 
    bean:Spring AOP扩展的,AspectJ没有对于指示符,用于匹配特定名称的Bean对象的 执行方法; 
    reference pointcut:表示引用其他命名切入点,只有@ApectJ风格支持,Schema风 格不支持。

切入点表达式的通配符

AspectJ类型匹配的通配符: 
    *:匹配任何数量字符; 
    ..:匹配任何数量字符的重复,如在类型模式中匹配任何数量子包;而在方法参数模式 中匹配任何数量参数。 
    +:匹配指定类型的子类型;仅能作为后缀放在类型模式后边。 说明: java.lang.String 匹配String类型; 
    java.*.String 匹配java包下的任何“一级子包”下的String类型; 如匹配java.lang.String,但不匹配java.lang.ss.String 
    java..* 匹配java包及任何子包下的任何类型; 如匹配java.lang.String、java.lang.annotation.Annotation 
    java.lang.*ing 匹配任何java.lang包下的以ing结尾的类型; 
    java.lang.Number+ 匹配java.lang包下的任何Number的自类型; 如匹配java.lang.Integer,也匹配java.math.BigInteger 

切入点表达式的逻辑条件

&& an
|| or
! not

Pointcut表达式类型

标准的AspectJ Aop的pointcut的表达式类型是很丰富的,但是Spring Aop只支持其中的9种,外加Spring Aop自己扩充的一种一共是11(10+1)种类型的表达式,分别如下。

  1. execution:一般用于指定方法的执行,用的最多。
  2. within:指定某些类型的全部方法执行,也可用来指定一个包。
  3. this:Spring Aop是基于动态代理的,生成的bean也是一个代理对象,this就是这个代理对象,当这个对象可以转换为指定的类型时,对应的切入点就是它了,Spring Aop将生效。
  4. target:当被代理的对象可以转换为指定的类型时,对应的切入点就是它了,Spring Aop将生效。
  5. args:当执行的方法的参数是指定类型时生效。
  6. @target:当代理的目标对象上拥有指定的注解时生效。
  7. @args:当执行的方法参数类型上拥有指定的注解时生效。
  8. @within:与@target类似,看官方文档和网上的说法都是@within只需要目标对象的类或者父类上有指定的注解,则@within会生效,而@target则是必须是目标对象的类上有指定的注解。而根据笔者的测试这两者都是只要目标类或父类上有指定的注解即可。
  9. @annotation:当执行的方法上拥有指定的注解时生效。
  10. reference pointcut:(经常使用)表示引用其他命名切入点,只有@ApectJ风格支持,Schema风格不支持
  11. bean:当调用的方法是指定的bean的方法时生效。(Spring AOP自己扩展支持的)

Pointcut定义时,还可以使用&&、||、! 这三个运算。进行逻辑运算。可以把各种条件组合起来使用

AspectJ切入点支持的切入点指示符还有:call、get、set、preinitialization、staticinitialization、initialization、handler、adviceexecution、withincode、cflow、cflowbelow、if、@this、@withincode;但Spring AOP目前不支持这些指示符,使用这些指示符将抛出IllegalArgumentException异常。这些指示符Spring AOP可能会在以后进行扩展

aspectj支持的所有切点表达式类型如下(但Spring目前只支持如上)
org.aspectj.weaver.tools.PointcutPrimitive这个枚举类:

// 相当于AspectJ一共提供了24中之多(当然不包含Spring自己的bean的模式)
public final class PointcutPrimitive extends TypeSafeEnum {

    public static final PointcutPrimitive CALL = new PointcutPrimitive("call",1);
    public static final PointcutPrimitive EXECUTION = new PointcutPrimitive("execution",2);
    public static final PointcutPrimitive GET = new PointcutPrimitive("get",3);
    public static final PointcutPrimitive SET = new PointcutPrimitive("set",4);
    public static final PointcutPrimitive INITIALIZATION = new PointcutPrimitive("initialization",5);
    public static final PointcutPrimitive PRE_INITIALIZATION = new PointcutPrimitive("preinitialization",6);
    public static final PointcutPrimitive STATIC_INITIALIZATION = new PointcutPrimitive("staticinitialization",7);
    public static final PointcutPrimitive HANDLER = new PointcutPrimitive("handler",8);
    public static final PointcutPrimitive ADVICE_EXECUTION = new PointcutPrimitive("adviceexecution",9);
    public static final PointcutPrimitive WITHIN = new PointcutPrimitive("within",10);
    public static final PointcutPrimitive WITHIN_CODE = new PointcutPrimitive("withincode",11);
    public static final PointcutPrimitive CFLOW = new PointcutPrimitive("cflow",12);
    public static final PointcutPrimitive CFLOW_BELOW = new PointcutPrimitive("cflowbelow",13);
    public static final PointcutPrimitive IF = new PointcutPrimitive("if",14);
    public static final PointcutPrimitive THIS = new PointcutPrimitive("this",15);
    public static final PointcutPrimitive TARGET = new PointcutPrimitive("target",16);
    public static final PointcutPrimitive ARGS = new PointcutPrimitive("args",17);
    public static final PointcutPrimitive REFERENCE = new PointcutPrimitive("reference pointcut",18);
    public static final PointcutPrimitive AT_ANNOTATION = new PointcutPrimitive("@annotation",19);
    public static final PointcutPrimitive AT_THIS = new PointcutPrimitive("@this",20);
    public static final PointcutPrimitive AT_TARGET = new PointcutPrimitive("@target",21);
    public static final PointcutPrimitive AT_ARGS = new PointcutPrimitive("@args",22);
    public static final PointcutPrimitive AT_WITHIN = new PointcutPrimitive("@within",23);
    public static final PointcutPrimitive AT_WITHINCODE = new PointcutPrimitive("@withincode",24);

    private PointcutPrimitive(String name, int key) {
        super(name, key);
    }

}

切入点表达式关键字使用示例

execution:
execution是使用的最多的一种Pointcut表达式,表示某个方法的执行,其标准语法如下。

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
  • 修饰符匹配(modifier-pattern?)
  • 返回值匹配(ret-type-pattern)可以为*表示任何返回值,全路径的类名等
  • 类路径匹配(declaring-type-pattern?)
  • 方法名匹配(name-pattern)可以指定方法名 或者 代表所有, set 代表以set开头的所有方法
  • 参数匹配((param-pattern))可以指定具体的参数类型,多个参数间用“,”隔开,各个参数也可以用“”来表示匹配任意类型的参数,如(String)表示匹配一个String参数的方法;(,String) 表示匹配有两个参数的方法,第一个参数可以是任意类型,而第二个参数是String类型;可以用(…)表示零个或多个任意参数
  • 异常类型匹配(throws-pattern?)
  • 其中后面跟着“?”的是可选项

下面看几个例子:

//表示匹配所有方法  
1)execution(* *(..))  
//表示匹配com.fsx.run.UserService中所有的公有方法  
2)execution(public * com.fsx.run.UserService.*(..))  
//表示匹配com.fsx.run包及其子包下的所有方法
3)execution(* com.fsx.run..*.*(..))

Pointcut定义时,还可以使用&&、||、! 这三个运算。进行逻辑运算

// 签名:消息发送切面
@Pointcut("execution(* com.fsx.run.MessageSender.*(..))")
private void logSender(){}
// 签名:消息接收切面
@Pointcut("execution(* com.fsx.run.MessageReceiver.*(..))")
private void logReceiver(){}
// 只有满足发送  或者  接收  这个切面都会切进去
@Pointcut("logSender() || logReceiver()")
private void logMessage(){}

这个例子中,logMessage()将匹配任何MessageSender和MessageReceiver中的任何方法。
当我们的切面很多的时候,我们可以把所有的切面放到单独的一个类去,进行统一管理,比如下面:

//集中管理所有的切入点表达式
public class Pointcuts {

@Pointcut("execution(* *Message(..))")
public void logMessage(){}

@Pointcut("execution(* *Attachment(..))")
public void logAttachment(){}

@Pointcut("execution(* *Service.*(..))")
public void auth(){}
}

这样别的使用时,采用全类名+方法名的方式

@Before("com.fsx.run.Pointcuts.logMessage()")
public void before(JoinPoint joinPoint) {
    System.out.println("Logging before " +       joinPoint.getSignature().getName());
}

within:
within是用来指定类型的,指定类型中的所有方法将被拦截。

// AService下面所有外部调用方法,都会拦截。备注:只能是AService的方法,子类不会拦截的
@Pointcut("within(com.fsx.run.service.AService)")
public void pointCut() {
}

所以此处需要注意:上面写的是AService接口,是达不到拦截效果的,只能写实现类:

//此处只能写实现类
@Pointcut("within(com.fsx.run.service.impl.AServiceImpl)")
public void pointCut() {
}

匹配包以及子包内的所有类:

@Pointcut("within(com.fsx.run.service..*)")
public void pointCut() {
}

this:
Spring Aop是基于代理的,target则表示被代理的目标对象。当被代理的目标对象可以被转换为指定的类型时则表示匹配。 注意:和上面不一样,这里是target,因此如果要切入,只能写实现类了

@Pointcut("target(com.fsx.run.service.impl.AServiceImpl)")
public void pointCut() {
}

args:
args用来匹配方法参数的。

  1. “args()”匹配任何不带参数的方法。
  2. “args(java.lang.String)”匹配任何只带一个参数,而且这个参数的类型是String的方法。
  3. “args(…)”带任意参数的方法。
  4. “args(java.lang.String,…)”匹配带任意个参数,但是第一个参数的类型是String的方法。
  5. “args(…,java.lang.String)”匹配带任意个参数,但是最后一个参数的类型是String的方法。
@Pointcut("args()")
public void pointCut() {
}

这个匹配的范围非常广,所以一般和别的表达式结合起来使用

@target:
@target匹配当被代理的目标对象对应的类型及其父类型上拥有指定的注解时。

//能够切入类上(非方法上)标准了MyAnno注解的所有外部调用方法
@Pointcut("@target(com.fsx.run.anno.MyAnno)")
public void pointCut() {
}

@args:
@args匹配被调用的方法上含有参数,且对应的参数类型上拥有指定的注解的情况。 例如:

// 匹配**方法参数类型上**拥有MyAnno注解的方法调用。如我们有一个方法add(MyParam param)接收一个MyParam类型的参数,而MyParam这个类是拥有注解MyAnno的,则它可以被Pointcut表达式匹配上
@Pointcut("@args(com.fsx.run.anno.MyAnno)")
public void pointCut() {
}

@within:
@within用于匹配被代理的目标对象对应的类型或其父类型拥有指定的注解的情况,但只有在调用拥有指定注解的类上的方法时才匹配。

“@within(com.fsx.run.anno.MyAnno)”匹配被调用的方法声明的类上拥有MyAnno注解的情况。比如有一个ClassA上使用了注解MyAnno标注,并且定义了一个方法a(),那么在调用ClassA.a()方法时将匹配该Pointcut;如果有一个ClassB上没有MyAnno注解,但是它继承自ClassA,同时它上面定义了一个方法b(),那么在调用ClassB().b()方法时不会匹配该Pointcut,但是在调用ClassB().a()时将匹配该方法调用,因为a()是定义在父类型ClassA上的,且ClassA上使用了MyAnno注解。但是如果子类ClassB覆写了父类ClassA的a()方法,则调用ClassB.a()方法时也不匹配该Pointcut。

@annotation:使用得也比较多
@annotation用于匹配方法上拥有指定注解的情况。

// 可以匹配所有方法上标有此注解的方法
@Pointcut("@annotation(com.fsx.run.anno.MyAnno)")
public void pointCut() {
}

我们还可以这么写,非常方便的获取到方法上面的注解

@Before("@annotation(myAnno)")
public void doBefore(JoinPoint joinPoint, MyAnno myAnno) {
    System.out.println(myAnno); //@com.fsx.run.anno.MyAnno()
    System.out.println("AOP Before Advice...");
}

reference pointcut:切入点引用(使用得非常多)

@Aspect
public class HelloAspect {
    @Pointcut("execution(* com.fsx.service.*.*(..)) ")
    public void point() {
    }
    // 这个就是一个`reference pointcut`  甚至还可以这样 @Before("point1() && point2()")
    @Before("point()")  
    public void before() {
        System.out.println("this is from HelloAspect#before...");
    }
}

bean: 这是Spring增加的一种方法,spring独有
bean用于匹配当调用的是指定的Spring的某个bean的方法时。 1、“bean(abc)”匹配Spring Bean容器中id或name为abc的bean的方法调用。 2、“bean(user*)”匹配所有id或name为以user开头的bean的方法调用。

// 这个就能切入到AServiceImpl类的素有的外部调用的方法里
@Pointcut("bean(AServiceImpl)")
public void pointCut() {
}

类型匹配语法

*:匹配任何数量字符; …:匹配任何数量字符的重复,如在类型模式中匹配任何数量子包;而在方法参数模式中匹配任何数量参数。 +:匹配指定类型的子类型;仅能作为后缀放在类型模式后边。

java.lang.String    匹配String类型; 
java.*.String       匹配java包下的任何“一级子包”下的String类型; 如匹配java.lang.String,但不匹配java.lang.ss.String 
java..*            匹配java包及任何子包下的任何类型。如匹配java.lang.String、java.lang.annotation.Annotation 
java.lang.*ing      匹配任何java.lang包下的以ing结尾的类型;
java.lang.Number+  匹配java.lang包下的任何Number的子类型; 如匹配java.lang.Integer,也匹配java.math.BigInteger 

表达式的组合

表达式的组合其实就是对应的表达式的逻辑运算,与、或、非。可以通过它们把多个表达式组合在一起。 1、“bean(userService) && args()”匹配id或name为userService的bean的所有无参方法。 2、“bean(userService) || @annotation(MyAnnotation)”匹配id或name为userService的bean的方法调用,或者是方法上使用了MyAnnotation注解的方法调用。 3、“bean(userService) && !args()”匹配id或name为userService的bean的所有有参方法调用。

posted @ 2022-08-01 09:30  飞_2016  阅读(1371)  评论(0编辑  收藏  举报