springboot

Springboot AOP 二:Pointcut表达式

2021-05-31  本文已影响0人  IT前沿技术分享

表示式(expression)和签名(signature)

//Pointcut表示式
@Pointcut("execution(* com.savage.aop.MessageSender.*(..))")
//Point签名
private void log(){} 

表达式类型及结构

表达式类型包括:

表达式格式

表达式可以通过 &&、 ||、 !、 的方式进行组合。

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?) 

其中后面跟着“?”的是可选项

括号中各个pattern分别表示:

举例说明.

execution(public * *(..))
execution(* set*(..))
execution(* com.xyz.service.AccountService.*(..))
execution(* com.xyz.service.*.*(..))
execution(* com.xyz.service..*.*(..))

第一个表示匹配任意的方法返回值, ..(两个点)表示零个或多个,第一个..表示service包及其子包,第二个表示所有类, 第三个*表示所有方法,第二个..表示方法的任意参数个数

execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))")
within(com.test.spring.aop.pointcutexp.*)
within(com.test.spring.aop.pointcutexp..*)
this(com.test.spring.aop.pointcutexp.Intf)

当一个实现了接口的类被AOP的时候,用getBean方法必须cast为接口类型,不能为该类的类型

    @within(org.springframework.transaction.annotation.Transactional)
    @target(org.springframework.transaction.annotation.Transactional)
@annotation(org.springframework.transaction.annotation.Transactional)

@within和@target针对类的注解,@annotation是针对方法的注解

@args(org.springframework.transaction.annotation.Transactional)
args(String)

织入

先来看一个列子

@AfterReturning(            
      pointcut="execution(* com.abc.service.*.access*(..)) && args(time, name)",            
      returning="returnValue")    
public void access(Date time, Object returnValue, String name) {      
    System.out.println("目标方法中的参数String = " + name);            
    System.out.println("目标方法中的参数Date = " + time);          
    System.out.println("目标方法的返回结果returnValue = " + returnValue);    
}

表达式中增加了args(time, name)部分,意味着可以在增强处理的签名方法(access方法)中定义"time"和"name"两个属性。

这两个形参的类型可以随意指定(access方法中指定),但一旦指定了这两个参数的类型,则这两个形参类型将用于限制该切入点只匹配第一个参数类型为Date, 第二个参数类型为String的方法(方法参数个数和类型若有不同均不匹配);

access方法只需要满足"time", "name"参数的顺序和pointcut中args(param1, param2)的顺序相同即可,"returnValue"位置顺序无所谓。

//将被access方法匹配
public String accessAdvice(Date d, String n) {    
    System.out.println("方法:accessAdvice");    
    return "aa";
}
上一篇 下一篇

猜你喜欢

热点阅读