Spring实战学习笔记 --面向切面的Spring(AOP)

本文详细介绍了Spring的面向切面编程(AOP)特性,包括切面、AOP术语、切点配置、在XML和注解中声明切面、通知参数传递等内容。通过实例展示了如何在Spring中实现和配置切面,帮助读者深入理解Spring AOP的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

切面

集成和委托是最常见的实现重用通用功能的面向对象技术,如果整个系统继承相同的基类,往往会导致一个脆弱的对象系统。
切面提供了另一种选择。切面帮助我们模块化横切关注点,而且在很多场景下更清晰简洁。横切关注点可以被模块化为特殊的类,这些特殊的类成为切面,我们通过声明可以定义这些切面以何种方式在何种地方应用,而无需修改受影响的类。


AOP术语

这里写图片描述

1、横切关注点(Advice)

对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点

Spring切面可以应用5种类型的通知:

Before:在方法被调用之前调用通知;
After:在方法调用之后调用通知;
After-returning:在方法成功执行后;
After-throwing:在方法抛出异常后;
Around:在方法调用之前和之后都会调用通知;

2、切面(Aspect)

切面就是对横切关注点的抽象,包括配置通知,切点,连接点等

3、连接点(Joinpoint)

被拦截到的点【应用执行过程/类 中能够插入切面的一个点/方法】,
因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法
实际上连接点还可以是字段或者构造器【AspjectJ】

4、切点(Pointcut)

对连接点进行拦截的定义,
匹配通知所要织入的一个或多个连接点,通常使用表达式匹配

5、通知(Advice)

所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类

6、目标对象(Target)

代理的目标对象

7、织入(Weaving)

将切面应用到目标对象并导致代理对象创建的过程。

在目标对象的生命周期里有多个点可以进行织入:

编译期:需要特殊的编译器,AspectJ的织入编译器就是这种方式;
类加载期:在目标类加载到JVM时被织入,需要特殊的类加载器。
运行期:在应用运行的某个时刻被织入,一般情况下,在织入切面时,AOP容器会为目标对象动态地创建一个代理对象。Spring AOP就是这种方式。

8、引入(Introduction)

在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段。


配置Pointcut(切点)

切点用于准确定位应该在什么地方应用切面的通知。Spring AOP需要使用AspectJ的切点表达式来定义切点

编写切点:
这里写图片描述

这里写图片描述

AspectJ 切点表达式如下:

AspectJ指示器描述
arg()限制连接点匹配参数为指定类型的执行方法
@args()限制连接点匹配参数由指定注解标注的执行方法
execution()用于匹配是连接点的执行方法
this()限制连接点匹配AOP代理的Bean引用为指定类型的类
target()限制连接点匹配目标对象为执行类型的类
@target()限制连接点匹配特定的执行对象,这些对象对应的类要具备指定类型的注解
within()限制连接点匹配指定的类型
@within()限制连接点匹配指定注解所标注的类型
@annotation()限制匹配带有指定注解连接点

Demo

(1)execution:用来匹配执行方法的连接点

//第一个*表示匹配任意的方法返回值,..(两个点)表示零个或多个参数,
//上面的第一个*表示service包及其子包,
//第二个*表示所有类,第三个*表示所有方法,第二个..表示方法的任意参数个数
A:@Pointcut("execution(* com.aijava.springcode.service..*.*(..))")

//within限定匹配方法的连接点,上面的就是表示匹配service包下的任意连接点
B:@Pointcut("within(com.aijava.springcode.service.*)")

//this用来限定AOP代理必须是指定类型的实例,如上,指定了一个特定的实例,就是UserService
C:@Pointcut("this(com.aijava.springcode.service.UserService)")

//bean也是非常常用的,bean可以指定IOC容器中的bean的名称
D:@Pointcut("bean(userService)")

在XML中声明切面

AspectJ指示器描述
< aop:advisor>定义AOP通知器
< aop:after>定义AOP后置通知(不管该方法是否执行成功)
< aop:after-returning>在方法成功执行后调用通知
< aop:after-throwing>在方法抛出异常后调用通知
< aop:around>定义AOP环绕通知
< aop:aspect>定义切面
< aop:aspect-autoproxy>定义@AspectJ注解驱动的切面
< aop:before>定义AOP前置通知
< aop:config>顶层的AOP配置元素,大多数的< aop:*>包含在< aop:config>元素内
< aop:declare-parent>为被通知的对象引入额外的接口,并透明的实现
< aop:pointcut>定义切点

前置、后置通知 demo:

<bean id="helloWorldImpl1" class="com.xrq.aop.HelloWorldImpl1" />
<bean id="helloWorldImpl2" class="com.xrq.aop.HelloWorldImpl2" />
<bean id="timeHandler" class="com.xrq.aop.TimeHandler" />
<bean id="logHandler" class="com.xrq.aop.LogHandler" />

<aop:config>
    <aop:aspect id="time" ref="timeHandler" order="1">
        <aop:pointcut id="addTime" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
        <aop:before method="printTime" pointcut-ref="addTime" />
        <aop:after method="printTime" pointcut-ref="addTime" />
    </aop:aspect>

    <aop:aspect id="log" ref="logHandler" order="2">
        <aop:pointcut id="printLog" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
        <aop:before method="LogBefore" pointcut-ref="printLog" />
        <aop:after method="LogAfter" pointcut-ref="printLog" />
    </aop:aspect>
</aop:config>

环绕通知:
使用环绕通知可以完成之前前置和后置所实现的相同功能,而且只需一个方法。不用担心多线程调用时,前置方法与后置方法的并发问题。

环绕通知通知 demo:

<bean id="audience" class="com.springinaction.springidol.AroundAudience" />

<aop:config>
   <aop:aspect ref="audience"><!-- 引用audience Bean -->
       <!-- 声明切入点 -->
       <aop:pointcut id="performance"
           expression="execution(* com.springinaction.springidol.Performer.perform(..))" />
       <aop:around method="watchPerformance" pointcut-ref="performance" />
   </aop:aspect>
</aop:config>

为通知传递参数

通过配置实现将被通知方法的参数传递给通知:

Demo 类

public interface MindReader {
    void interceptThoughts(String thoughts);
    String getThoughts();
}
public class Magician implements MindReader {
    private String thoughts;
    @Override
    public void interceptThoughts(String thoughts) {
        System.out.println("Intercepting volunteer's thoughts");
        this.thoughts = thoughts;
    }

    @Override
    public String getThoughts() {
        return thoughts;
    }
}

public interface Thinker {
    void thinkOfSomething(String thoughts);
}

public class Volunteer implements Thinker {
    private String thoughts;
    @Override
    public void thinkOfSomething(String thoughts) {
        System.out.println("Thinker: " + thoughts);
        this.thoughts = thoughts;
    }
    public String getThoughts() {
        return thoughts;
    }
}

XML配置文件

<bean id="volunteer" class="com.springinaction.springidol.Volunteer" />
<bean id="magician" class="com.springinaction.springidol.Magician" />

<aop:config>
 <aop:aspect ref="magician"><!-- 引用magician Bean -->
     <!-- 声明切入点 -->
     <aop:pointcut id="thinking"
         expression="execution(* com.springinaction.springidol.Thinker.thinkOfSomething(String)) and args(thoughts) " />
         <!-- 注意这里定义了arg-names -->
     <aop:before method="interceptThoughts" pointcut-ref="thinking" arg-names="thoughts" />
 </aop:aspect>
</aop:config>

切入点指定了Thinker的thinkOfSomething()方法,指定了String参数,然后在args参数中标识了将thoughts作为参数。

同时,< aop:before>引用了thoughts参数,标识该参数必须传递给magician的interceptThoughts()方法。

注意: < aop:before>引用的thoughts参数和pointcut标识的thoughts参数,二者名称必须一致!


在注解中使用切面

使用配置注解,首先我们要将切面在spring上下文中声明成自动代理bean,即

<aop:aspectj-autoproxy />

Demo :

@Aspect
public class AspectJAudience {

    // 定义切点,切点名称来自于注解所对应的方法名称
    //performance()本身只是个标示,供@pointcut注解依附  
    @Pointcut("execution(* com.springinaction.springidol.Performer.perform(..))")
    public void performance() {
    }

    // 表演之前
    @Before("performance()")
    public void takeSeats() {
        System.out.println("The audience is taking their seats.");
    }

    // 表演之前
    @Before("performance()")
    public void turnOffCellPhones() {
        System.out.println("The audience is turning off their cellphones");
    }

    // 表演之后
    @AfterReturning("performance()")
    public void applaud() {
        System.out.println("CLAP CLAP CLAP CLAP CLAP");
    }

    // 表演失败之后
    @AfterThrowing("performance()")
    public void demandRefund() {
        System.out.println("Boo! We want our money back!");
    }
}

环绕注解:

@Aspect
public class AspectJAroundAudience {

    // 定义切点
    @Pointcut("execution(* com.springinaction.springidol.Performer.perform(..))")
    public void performance() {
    }

    @Around("performance()")
    public void watchPerformance(ProceedingJoinPoint joinpoint) {
        try {
            // 表演之前
            System.out.println("The audience is taking their seats.");
            System.out.println("The audience is turning off their cellphones");
            long start = System.currentTimeMillis();

            // 执行被通知的方法
            joinpoint.proceed();

            // 表演之后
            long end = System.currentTimeMillis();
            System.out.println("CLAP CLAP CLAP CLAP CLAP");
            System.out.println("The performance took " + (end - start) + " milliseconds.");
        } catch (Throwable t) {
            // 表演失败之后
            System.out.println("Boo! We want our money back!");
        }
    }
}

传递参数的通知:

@Aspect
public class AspectJMagician implements MindReader {
    private String thoughts;

    @Pointcut("execution(* com.springinaction.springidol.Thinker.thinkOfSomething(String)) && args(thoughts))")
    public void thinking(String thoughts){        
    }

    //Before注解里不需要arg-names属性
    @Override
    @Before("thinking(thoughts)")
    public void interceptThoughts(String thoughts) {
        System.out.println("Intercepting volunteer's thoughts");
        this.thoughts = thoughts;
    }

    @Override
    public String getThoughts() {
        return thoughts;
    }

}

XML与注解都可以把一个POJO转变为一个切面的有效方式,二者最大的区别是:
@AspjectJ需要实现切面功能的源码,XML中< aop:aspect>可以使用任意的一个Bean


Spring对AOP的支持

Spring中AOP代理由Spring的IOC容器负责生成、管理,其依赖关系也由IOC容器负责管理,
Spring创建代理的规则为:

1、默认使用Java动态代理来创建AOP代理,这样就可以为任何接口实例创建代理了
2、当需要代理的类不是代理接口的时候,Spring会切换为使用CGLIB代理,也可强制使用CGLIB

高版本的Spring会自动选择是使用动态代理还是CGLIB生成代理内容,当然我们也可以强制使用CGLIB生成代理,
那就是< aop:config>里面有一个”proxy-target-class”属性,这个属性值如果被设置为true,那么基于类的代理将起作用,如果proxy-target-class被设置为false或者这个属性被省略,那么基于接口的代理将起作用。

参考文章:
https://www.jianshu.com/p/404cd64ef5a5

参考文章:
http://www.cnblogs.com/xrq730/p/4919025.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值