SpringAOP表达式及五种Advice

SpringAOP表达式

SpringAOP表达式由三部分组成:

  1. 指示器(Designators)
  2. 通配符(WildCards)
  3. 运算符(Operators)
  • 指示器

  1. 匹配方法:execution()
  2. 匹配注解:@target,@args,@within,@annotation
  3. 匹配包/类型:within()
  4. 匹配对象:this(),bean(),target()
  5. 匹配参数:args()

1.匹配方法:

execution表达式的格式

{

    modidier-pattern?修饰符

    ret-type-pattern 返回值

    declaring-type-pattern?声明的包名

    name-pattern(param-pattern)声明的方法名(参数名)

    throws-pattern?声明的抛出的异常

}

以上带有?的部分可以缺省,其他部分则必须声明

例如:@Pointcut("execution(public * com.test.service.*Service.*(..))")

表示拦截访问控制为public ,返回值为任意类型,位于com.test.service包下任意以Service结尾的类中的任意参数的任意方法。

如果想要拦截符合上述条件的某些会抛出异常的方法则直接在表达式后加上throws 要抛出的异常即可。

2.匹配注解:

@Pointcut("@annotation(com.test.security.AdminOnly)")

拦截带有com.test.security.AdminOnly注解的方法

@Pointcut("@within(com.google.common.annotation.Beta)")

拦截标注有Beta的类中的方法,要求的annotation的RetentionPolicy级别为CLASS

@Pointcut("@target(org.springframework.stereotype.Reposity)")

拦截标注有Reposity的类中的方法,要求的annotation的RetentionPolicy级别为RUNTIME

@Pointcut("@args(org.springframework.stereotype.Reposity)")

拦截方法中的参数的类标注有Reposity注解的方法

其中@target和@within在spring context下是没有以上的区别的

3.匹配包:

@Pointcut("within(com.test.service.UserService)")

拦截com.test.service下UserService类中的所有方法

@Pointcut("within(com.test.service..*)")

拦截com.test.service包及其子包下所有类的方法

4.匹配对象:

@Pointcut("this(com.test.Dao.UserDao)")

拦截的目标对象为指定的UserDao类型的方法,this拦截的是UserDao的AOP代理对象的方法

@Pointcut("target(com.test.Dao.UserDao)")

拦截的目标对象为指定的UserDao类型的方法,target拦截的是UserDao对象的方法,而不是对应的AOP代理对象的方法

在使用introduction动态的添加方法时,this能够拦截到,而target拦截不到。

@Pointcut("bean(*Service)")

拦截所有以Service结尾的bean中的方法

5.匹配参数:

@Pointcut("execution(* *. . find*(Long))")

拦截任何以find开头的只有一个Long类型参数的方法

@Pointcut("args(Long)")

拦截任何只有一个Long参数的方法

@Pointcut("execution(* *. .find*(Long,..))")

拦截任何以find开头且第一个参数为Long类型的方法

@Pointcut("args(Long,..)")

拦截任何第一个参数为Long类型的方法

  • 通配符

*匹配任意的数量的字符

..匹配任意数目的子包或参数

+匹配指定类及其子类

  • 运算符

&&逻辑与运算

||逻辑或运算

!逻辑非运算

Advice

1.@Before 前置通知

2.@After 后置通知,方法执行完之后

3.@AfterReturnning 返回通知,成功执行之后

4.@AfterThrowing 异常通知,抛出异常之后

5.@Around 环绕通知(方法执行前后都有通知)

其中在@Before通知中可以获取拦截方法的参数值,例如:

@Before(value="matchArgs() && args(userId)"),可以获取userId的值

在@AfterReturnning中可以绑定返回结果,例如:

@AfterReturnning(value="matchReturn() ,returnning=returnValue"),把返回值和returnValue绑定

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卷福。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值