切入点@Pointcut的使用
在确定切面aspect之后,需要在切面上确定切入点pointcut
定义
注解@pointcut("{切入点}")
其中{切入点}格式如下:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)
参数 | 说明 |
---|---|
modifiers-pattern | 修饰匹配 |
ret-type-pattern | 返回值匹配:可以为*表示任何返回值,全路径的类名等 |
declaring-type-pattern | 类路径匹配 |
name-pattern | 方法名匹配:以指定方法名 或者 代表所有, set 代表以set开头的所有方法 |
param-pattern | 参数匹配:可以指定具体的参数类型,多个参数间用“,”隔开,各个参数也可以用“”来表示匹配任意类型的参数,如(String)表示匹配一个String参数的方法;(,String) 表示匹配有两个参数的方法,第一个参数可以是任意类型,而第二个参数是String类型;可以用(…)表示零个或多个任意参数 |
throws-pattern | 异常类型匹配 |
PS: 其中后面带“?”的为可选项;
一个切面aspect可以定义多个切入点pointcut,并支持运算符 || 、&& 、!
@Pointcut("execution(public * com.xhwl.seven.controller..*Controller.*(..))")
public void pointCut1(){}
@Pointcut("execution(public * com.xhwl.seven.controller..*Service.*(..))")
public void pointCut2(){}
@Pointcut("pointCut1() || pointCut2()")
public void pointCut3(){}
使用
定义完Pointcut之后,可在通知 advice 上定义使用
@Before("pointCut2()")
@AfterReturning(returning = "o", pointcut = "pointCut3()")
切入点的表达式
常用的表达式为execution表达式,execution匹配的就是连接点(Joinpoint,一般是方法),看上面的表达式execution是固定的,方法的修饰符是可选的,返回类型是必须的,定义的全限类型也是可选的,名称是必须的,参数是必须的,这些都可以使用通配符。
除了execution表达式,还有以下几种:
- within:包名下所有方法
- this:指定类本身、继承该类、实现该接口 等所有方法
- target:指定类本身、继承该类、实现该接口 等所有方法
- annotation:任何使用指定注解的方法
如:
//指定包下所有方法
@Around("within(com.kellan.test..*)")
//所有使用了Transactional注解的方法
@Around("@annotation(org.springframework.transaction.annotation.Transactional)")
//指定TestService类本身、继承该类、实现该接口 等所有方法;
@Around("this(com.aop.service.TestService)")
@Around("target(com.aop.service.TestService)")