Spring学习笔记(八、Spring对AspectJ的支持)

上一篇:Spring学习笔记(七、Spring AOP API)

一、AspectJ介绍与Pointcut注解应用

1. AspectJ

  • @AspectJ的风格类似纯java注解的普通java类。
  • Spring可以使用AspectJ来做切入点分析。
  • AOP的运行时仍旧是纯的Spring AOP,对AspectJ的编译器或者织入无依赖性。

2. Spring中配置AspectJ

  • 对@AspectJ支持可以使用XML或Java风格配置。
  • 确保AspectJ的aspectjweaver.jar库包含在应用程序(版本1.6.8或更高版本)的classpath中。


    Paste_Image.png

3. @Aspect注解

  • AspectJ切面使用@Aspect注解配置,拥有@Aspect注解的任何bean,将被Spring自动识别并应用。
  • 用@Aspect注解的类可以有方法和字段,他们也可能包括切入点(pointcut)、通知(advice)、和引入(introduction)声明。
  • @Aspect注解是不能通过类路径自动检测发现的,所以需要配合使用@Component注释或者在xml中配置bean。
  • 一个类中的@Aspect注解标识它为一个切面,并且将自己从自动代理中排除。

4. pointcut

  • 一个切入点通过一个普通的方法定义来提供,并且切入点表达式使用@Pointcut注解,方法返回类型必须为void。
指示符 说明
execution 匹配方法执行的连接点
within 限定匹配特定类型的连接点
this 匹配特定连接点的bean引用,是指定类型的实例的限制
target 限定匹配特定连接点的目标对象是指定类型的实例
args 限定匹配特定连接点的参数是给定类型的实例
@target 限定匹配特定连接点的类执行对象的具有给定类型的注解
@args 限定匹配特定连接点实际传入的参数的类型具有给定类型的注解
@within 限定匹配到内具有给定的注释类型的连接点
@annotation 限定匹配特定连接点的主体具有给定的注解

创建一个切面类:AmberAspect

package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspect {
    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut(){
    }
    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut(){}
}

5. 组合pointcut

  • 切入点表达式可以通过&&、||和!进行组合,也可以通过名字引用切入点表达式。
  • 通过组合,可以建立更加复杂的切入点表达式。


    Paste_Image.png

6. 定义良好的pointcuts

  • AspectJ是编译器的AOP。
  • 检查代码并匹配连接点与切入点的代价是昂贵的。
  • 一个好的切入点应该包括以下几点:
    • 选择特定类型的连接点。如:execution、get、set、call、handler
    • 确定连接点范围,如:within、withincode
    • 匹配上下文信息,如:this、target、@annotation

二、Advice定义及实例

1. Before advice
更新AmberAspect 切面类:

package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspect {
    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut(){
    }

    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut(){}

    @Before("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void before(){
        System.out.println("前置通知!");
    }
}

创建业务类AspectBiz :

package com.amber.aop.biz;
import org.springframework.stereotype.Service;
import test12.StringStore;
/**
 * Created by amber on 2017/6/18.
 * 业务类
 */
@Service
public class AspectBiz {
    public String save(String args){
        System.out.println("执行AspectBiz的save方法,参数:"+args);
        return "Save Success";
    }
}

applicationContext:

    <context:component-scan base-package="com.amber.aop"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

测试类:

  @Test
    public void test17() {
        AspectBiz aspectBiz=super.getBean("aspectBiz");
        aspectBiz.save("淡雅如菊,温润如玉");
    }

结果:


Paste_Image.png

修改AmberAspect 切面类,将前置通知的表达式替换成同样表达式的pointcut()方法:

 package com.amber.aop.aspectj;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspect {

    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut(){

    }
    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("前置通知!");
    }
}

结果:


Paste_Image.png

2. After Returning Advice

  • 有时候需要在通知体内得到返回的实际值,可以使用@AfterReturning绑定返回值的形式。
    更新AmberAspect 切面类,增加After Returning通知:
package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspect {
    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut(){

    }
    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("前置通知!");
    }

    @AfterReturning(pointcut = "bizPointcut()",returning = "returnValue")
    public void afterReturning(Object returnValue){
        System.out.println("返回后通知,返回值为:"+returnValue);
    }
}

结果:


Paste_Image.png

3. After throwing advice

  • 有时候需要在通知体内得到返回的实际值,可以使用@AfterThrowing绑定返回值的形式。
    更新AmberAspect 切面类,增加After Throwing通知:
package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspect {

    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut(){

    }
    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("前置通知!");
    }

    @AfterReturning(pointcut = "bizPointcut()",returning = "returnValue")
    public void afterReturning(Object returnValue){
        System.out.println("返回后通知,返回值为:"+returnValue);
    }

    @AfterThrowing(pointcut = "bizPointcut()",throwing = "e")
    public void afterThrowing(Exception e){
        System.out.println("异常后通知,异常为:"+e);
    }
}

修改类:

package com.amber.aop.biz;
import org.springframework.stereotype.Service;
import test12.StringStore;
/**
 * Created by amber on 2017/6/18.
 * 业务类
 */
@Service
public class AspectBiz {
    public String save(String args){
        System.out.println("执行AspectBiz的save方法,参数:"+args);
        throw new RuntimeException("Save failed");
        //return "Save Success";
    }
}

结果:


Paste_Image.png

3. After(finally) advice

  • 最终通知必须准备处理正常和异常两种返回情况,它通常用于释放资源。
    更新AmberAspect 切面类,增加After通知:
package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspect {
    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut(){

    }
    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("前置通知!");
    }

    @AfterReturning(pointcut = "bizPointcut()",returning = "returnValue")
    public void afterReturning(Object returnValue){
        System.out.println("返回后通知,返回值为:"+returnValue);
    }

    @AfterThrowing(pointcut = "bizPointcut()",throwing = "e")
    public void afterThrowing(Exception e){
        System.out.println("异常后通知,异常为:"+e);
    }

    @After("bizPointcut()")
    public void after(){
        System.out.println("后置通知!");
    }
}

结果:


Paste_Image.png

将业务类AspectBiz异常注释:

package com.amber.aop.biz;
import org.springframework.stereotype.Service;
import test12.StringStore;
/**
 * Created by amber on 2017/6/18.
 * 业务类
 */
@Service
public class AspectBiz {
    public String save(String args){
        System.out.println("执行AspectBiz的save方法,参数:"+args);
//        throw new RuntimeException("Save failed");
        return "Save Success";
    }
}

结果:


Paste_Image.png

4. Around advice

  • 环绕通知使用@Around注解来声明,通知方法的第一个参数必须是ProceedingJoinPoint类型。
  • 在通知内部会调用ProceedingJoinPoint的proceed()方法会导致执行真正的方法,传入一个Object[]对象,数组中的值将被作为参数传递给方法。
    更新AmberAspect ,增加Around通知:
package com.amber.aop.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspect {
    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut(){

    }
    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("前置通知!");
    }

    @AfterReturning(pointcut = "bizPointcut()",returning = "returnValue")
    public void afterReturning(Object returnValue){
        System.out.println("返回后通知,返回值为:"+returnValue);
    }

    @AfterThrowing(pointcut = "bizPointcut()",throwing = "e")
    public void afterThrowing(Exception e){
        System.out.println("异常后通知,异常为:"+e);
    }

    @After("bizPointcut()")
    public void after(){
        System.out.println("后置通知!");
    }

    @Around("bizPointcut()")
    public Object around(ProceedingJoinPoint pjp)throws Throwable{
        System.out.println("环绕通知,pjp.proceed();执行前!");
        Object obj=pjp.proceed();
        System.out.println("环绕通知,pjp.proceed();执行后!  返回值为:"+obj);
        return obj;
    }
}

结果:


Paste_Image.png

三、给Advice传递参数

1. 给Advice传递参数

Paste_Image.png

  1. 创建一个AmberAspectTwo切面类,增加带参的前置通知,传入普通参数,将之前的AmberAspect类的@Aspect注释掉:
package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspectTwo{

    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut() {
    }

    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut() {
    }

    @Pointcut("pointcut()&&args(arg)")
    public void before(String arg) {
        System.out.println("前置通知,获取参数为:" + arg);
    }
}

结果:


Paste_Image.png
  1. 创建一个自定义注解:
package com.amber.aop.aspectj;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by amber on 2017/6/20.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AmberMethod {
    String value();
}

修改业务类方法,为其添加一个自定义注解:

package com.amber.aop.biz;
import com.amber.aop.aspectj.AmberMethod;
import org.springframework.stereotype.Service;
import test12.StringStore;
/**
 * Created by amber on 2017/6/18.
 * 业务类
 */
@Service
public class AspectBiz {
    @AmberMethod("这是我自定义的注解")
    public String save(String args){
        System.out.println("执行AspectBiz的save方法,参数:"+args);
//        throw new RuntimeException("Save failed");
        return "Save Success";
    }
}

更新AmberAspectTwo切面类,增加带注解参数的后置通知:

package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspectTwo {

    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut() {
    }

    @Pointcut("within(com.amber.aop.biz.*)")
    public void bizPointcut() {
    }

    @Before("pointcut()&&args(arg)")
    public void beforeWithArgs(String arg) {
        System.out.println("前置通知,获取参数为:" + arg);
    }

    @After("pointcut()&&@annotation(amberMethod)")
    public void afterWithAnnotation(AmberMethod amberMethod) {
        System.out.println("后置通知,获取参数为:" + amberMethod.value());
    }
}

结果:


Paste_Image.png

修改AmberAspectTwo 切面类修改其后置通知的值引用bizPointcut()方法的组合切入点。

package com.amber.aop.aspectj;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
 * Created by amber on 2017/6/20.
 */
@Component
@Aspect
public class AmberAspectTwo {

    @Pointcut("execution(* com.amber.aop.biz.*Biz.*(..))")
    public void pointcut() {
    }

    @Pointcut("within(com.amber.aop.biz.*) && @annotation(amberMethod)")
    public void bizPointcut(AmberMethod amberMethod) {
    }

    @Before("pointcut()&&args(arg)")
    public void beforeWithArgs(String arg) {
        System.out.println("前置通知,获取参数为:" + arg);
    }

    @After("bizPointcut(amberMethod)")
    public void afterWithAnnotation(AmberMethod amberMethod) {
        System.out.println("后置通知,获取参数为:" + amberMethod.value());
    }
}

结果:


Paste_Image.png

2. Advice的参数及泛型

  • Spring AOP可以处理泛型类的声明和使用方法的参数。


    Paste_Image.png

3. Advice参数名称

  • 通知和切入点有一个额外的“argName”属性,它可以用来指定所注解的方法的参数名。


    Paste_Image.png
  • 如果第一个参数是JoinPoint,ProceedingJoinPoint,JoinPoint.StaticPart,那么可以忽略它。


    Paste_Image.png

3. Introductions

  • 允许一个切面声明一个通知对象实现指定接口,并且提供了一个接口实现类来代表这些对象。
  • Introduction使用@DeclareParents进行注解,这个注解用来定义匹配的类型拥有一个新的parent。


    Paste_Image.png

4. 切面实例化模型

  • 这是一个高级主题
  • “perthis” 切面通过指定@Aspect注解perthis子句实现。
  • 每个独立的service对象执行时都会创建一个切面实例。
  • service对象的每个方法在第一次执行的时候创建切面实例,切面在service对象失效的时候同时失效。


    Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容