Spring AOP详解

    技术2022-07-17  99

    1.简述 AOP 概念

    AOP:Aspect Oriented Program,面向(方面)切面的编程;Filter(过滤器)也是一种 AOP。AOP 是一种新的方法论,是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充。AOP 的主要编程对象是切面(aspect)。而切面模块化横切关注点。可以举例通过事务说明。

    简单来说:就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。

    2.Spring的AOP理解

    AOP,一般称为面向切面编程,作为面向对象的一种补充,用于将那些与业务无关,但却对多个对象产生影响的公共行为和逻辑,抽取并封装为一个可重用的模块,这个模块被命名为“切面”(Aspect),减少系统中的重复代码,降低了模块间的耦合度,同时提高了系统的可维护性。可用于权限认证、日志、事务处理。

    AOP实现的关键在于代理模式,AOP代理主要分为静态代理和动态代理。

    静态代理的代表为AspectJ;动态代理则以Spring AOP为代表。

    (1)AspectJ是静态代理的增强,所谓静态代理,就是AOP框架会在编译阶段生成AOP代理类,因此也称为编译时增强,他会在编译阶段将AspectJ(切面)织入到Java字节码中,运行的时候就是增强之后的AOP对象。

    (2)Spring AOP使用的动态代理,所谓的动态代理就是说AOP框架不会去修改字节码,而是每次运行时在内存中临时为方法生成一个AOP对象,这个AOP对象包含了目标对象的全部方法,并且在特定的切点做了增强处理,并回调原对象的方法。

    Spring AOP中的动态代理主要有两种方式,JDK动态代理和CGLIB动态代理:

    JDK动态代理只提供接口的代理,不支持类的代理。核心InvocationHandler接口和Proxy类,InvocationHandler 通过invoke()方法反射来调用目标类中的代码,动态地将横切逻辑和业务编织在一起;接着,Proxy利用 InvocationHandler动态创建一个符合某一接口的的实例, 生成目标类的代理对象。

    如果代理类没有实现 InvocationHandler 接口,那么Spring AOP会选择使用CGLIB来动态代理目标类。CGLIB(Code Generation Library),是一个代码生成的类库,可以在运行时动态的生成指定类的一个子类对象,并覆盖其中特定方法并添加增强代码,从而实现AOP。CGLIB是通过继承的方式做的动态代理,因此如果某个类被标记为final,那么它是无法使用CGLIB做动态代理的。

    静态代理与动态代理区别在于生成AOP代理对象的时机不同,相对来说AspectJ的静态代理方式具有更好的性能,但是AspectJ需要特定的编译器进行处理,而Spring AOP则无需特定的编译器处理。

    InvocationHandler 的 invoke(Object proxy,Method method,Object[] args):proxy是最终生成的代理实例; proxy 是代理对象的引用;method 是被代理目标实例的某个具体方法; args 是被代理目标实例某个方法的具体入参, 在方法反射调用时使用。

    3.Spring AOP里面的名词解释

    (1)切面(Aspect):被抽取的公共模块,可能会横切多个对象。 在Spring AOP中,切面可以使用通用类(基于模式的风格) 或者在普通类中以 @AspectJ 注解来实现。切点+通知。

    (2)连接点(Joinpoint):指方法,在Spring AOP中,一个连接点 总是 代表一个方法的执行。

    (3)通知(Advice):在切面的某个特定的连接点(Join point)上执行的动作。通知有各种类型,其中包括“around”、“before”和“after”等通知。许多AOP框架,包括Spring,都是以拦截器做通知模型, 并维护一个以连接点为中心的拦截器链。

    (4)切入点(Pointcut):切入点是指 我们要对哪些Join point进行拦截的定义。通过切入点表达式,指定拦截的方法,比如指定拦截add、search。

    (5)引入(Introduction):(也被称为内部类型声明(inter-type declaration))代理的目标对象。声明额外的方法或者某个类型的字段。Spring允许引入新的接口(以及一个对应的实现)到任何被代理的对象。例如,你可以使用一个引入来使bean实现 IsModified 接口,以便简化缓存机制。

    (6)目标对象(Target Object): 被一个或者多个切面(aspect)所通知(advise)的对象。也有人把它叫做 被通知(adviced) 对象。 既然Spring AOP是通过运行时代理实现的,这个对象永远是一个 被代理(proxied) 对象。

    (7)织入(Weaving):指把增强应用到目标对象来创建新的代理对象的过程。Spring是在运行时完成织入。

    (8)代理(Proxy): 一个类被 AOP 织入增强后,就产生一个结果代理类。

    切入点(pointcut)和连接点(join point)匹配的概念是AOP的关键,这使得AOP不同于其它仅仅提供拦截功能的旧技术。 切入点使得定位通知(advice)可独立于OO层次。 例如,一个提供声明式事务管理的around通知可以被应用到一组横跨多个对象中的方法上(例如服务层的所有业务操作)。

    4.动态代理

    1.基于接口的动态代理

    public class Test1 { @Test public void test1(){ //被代理类对象要声明为最终的 final Producer producer=new Producer(); /** * 动态代理: * 特点:字节码随用随创建,随用随加载 * 作用:不修改源码的基础上对方法增强 * 分类: * 基于接口的动态代理 * 基于子类的动态代理 * 基于接口的动态代理: * 涉及的类:Proxy * 提供者:JDK官方 * 如何创建代理对象: * 使用Proxy类中的newProxyInstance方法 * 创建代理对象的要求: * 被代理类最少实现一个接口,如果没有则不能使用 * newProxyInstance方法的参数: * ClassLoader:类加载器 * 它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法。 * Class[]:字节码数组 * 它是用于让代理对象和被代理对象相同方法。固定写法。 * InvocationHandler:用于提供增强的代码 * 它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。 * 此接口的实现类都是谁用谁写。 */ //代理对象和被代理类对象要实现同一个接口 IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(), new InvocationHandler() { /** * 作用:执行被代理对象的任何接口方法都会经过该方法 * 方法参数的含义 * @param proxy 代理对象的引用 * 1. 可以使用反射获取代理对象的信息(也就是proxy.getClass().getName()。 * 2. 可以将代理对象返回以进行连续调用,这就是proxy存在的目的,因为this并不是代理对象。 * @param method 当前执行的方法 * @param args 当前执行方法所需的参数 * @return 和被代理对象方法相同的返回值 * @throws Throwable */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object value=null; //获取方法执行的参数 //判断当前方法是不是销售 if ("saleProduct".equals(method.getName())){ Float money= (Float) args[0]; //两个参数:被代理类对象,方法增强的参数 value=method.invoke(producer,money*0.8f); } return value; } }); proxyProducer.saleProduct(10000f); } }

    IProducer 生产者的接口

    public interface IProducer { /** * 销售 * @param money */ public void saleProduct(float money); /** * 售后 * @param money */ public void afterService(float money); }

    Producer 生产者实现类:

    public class Producer implements IProducer{ /** * 销售 * @param money */ public void saleProduct(float money){ System.out.println("销售产品,并拿到钱:"+money); } /** * 售后 * @param money */ public void afterService(float money){ System.out.println("提供售后服务,并拿到钱:"+money); } }

    2.基于子类的动态代理

    public class Test4 { @Test public void test() { final Producer producer = new Producer(); /** * 动态代理: * 特点:字节码随用随创建,随用随加载 * 作用:不修改源码的基础上对方法增强 * 分类: * 基于接口的动态代理 * 基于子类的动态代理 * 基于子类的动态代理: * 涉及的类:Enhancer * 提供者:第方cglib库 * 如何创建代理对象: * 使用Enhancer类中的create方法 * 创建代理对象的要求: * 被代理类是最终类 * create方法的参数: * Class:字节码 * 它是用于指定被代理对象的字节码。 * * intercept:用于提供增强的代码 * 它是让我们写如何代理。我们一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。 * 此接口的实现类都是谁用谁写。 * 我们一般写的都是该接口的子接口实现类:MethodInterceptor */ Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() { /** * 执行被代理对象的任何方法都会经过该方法 * @param proxy * @param method * @param args * 以上个参数和基于接口的动态代理中invoke方法的参数是一样的 * @param methodProxy :当前执行方法的代理对象 * @return * @throws Throwable */ public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { //提供增强的代码 Object returnValue = null; //1.获取方法执行的参数 Float money = (Float) args[0]; //2.判断当前方法是不是销售 if ("saleProduct".equals(method.getName())) { returnValue = method.invoke(producer, money * 0.8f); } return returnValue; } }); cglibProducer.saleProduct(12000f); } }

    生产者类

    public class Producer { /** * 销售 * @param money */ public void saleProduct(float money){ System.out.println("销售产品,并拿到钱:"+money); } /** * 售后 * @param money */ public void afterService(float money){ System.out.println("提供售后服务,并拿到钱:"+money); } }

    3.使用动态代理对spring进行方法增强

    实现类:

    public class java1 implements MyInterface{ public int add(int a,int b){ return a+b; } public int del(int a,int b){ return a-b; } public int che(int a,int b){ return a*b; } public int div(int a,int b){ return a/b; } }

    BeanFactory 类

    public class BeanFactory { private java1 java; public void setJava(java1 java) { this.java = java; } public MyInterface getBean(){ MyInterface proxyJava = (MyInterface) Proxy.newProxyInstance( java.getClass().getClassLoader(), java.getClass().getInterfaces(), new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object value = null; System.out.println("方法执行前...."); value = method.invoke(java, args); System.out.println("方法执行之后...."); return value; } } ); return proxyJava; } }

    配置文件

    <bean id="factory" class="com.atguigu.factory.BeanFactory"> <property name="java" ref="java"></property> </bean> <bean id="java" class="com.atguigu.java1.java1"></bean> <bean id="proxyJava" factory-bean="factory" factory-method="getBean"></bean>

    测试类

    @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class Test1 { @Autowired @Qualifier("proxyJava") private MyInterface myInterface; @Test public void test1(){ System.out.println(myInterface.add(1, 2)); } @Test public void test2(){ System.out.println(myInterface.del(1, 2)); } @Test public void test3(){ System.out.println(myInterface.che(1, 2)); } @Test public void test4(){ System.out.println(myInterface.div(1, 2)); } }

    5.基于xml形式的配置

    1.步骤说明

    1、把通知Bean也交给spring来管理 2、使用aop:config标签表明开始AOP的配置 3、使用aop:aspect标签表明配置切面

    id属性:是给切面提供一个唯一标识ref属性:是指定通知类bean的Id。

    4、在aop:aspect标签的内部使用对应标签来配置通知的类型。 我们现在示例是让printLog方法在切入点方法执行之前:所以是前置通知。

    aop:before:表示配置前置通知

    method属性:用于指定Logger类中哪个方法是前置通知pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强

    例如:

    <aop:before method="printLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:before>

    2.切入点表达式的写法

    关键字:execution(表达式)

    表达式: 访问修饰符 返回值 包名.包名.包名…类名.方法名(参数列表)

    标准的表达式写法:

    public void com.itheima.service.impl.AccountServiceImpl.saveAccount()

    访问修饰符可以省略

    void com.itheima.service.impl.AccountServiceImpl.saveAccount()

    返回值可以使用通配符,表示任意返回值

    * com.itheima.service.impl.AccountServiceImpl.saveAccount()

    包名可以使用通配符,表示任意包。但是几级包,就需要写几个*.

    * *.*.*.*.AccountServiceImpl.saveAccount())

    包名可以使用…表示当前包及其子包

    * *..AccountServiceImpl.saveAccount()

    类名和方法名都可以使用*来实现通配

    * *..*.*()

    参数列表: 可以直接写数据类型:

    基本类型直接写名称 int引用类型写包名.类名的方式 java.lang.String可以使用通配符表示任意类型,但是必须参数可以使用…表示无参数均可,参数可以是任意类型

    全通配写法:

    * *..*.*(..)

    实际开发中切入点表达式的通常写法: 切到业务层实现类下的所方法

    * com.itheima.service.impl.*.*(..)

    3.通知类型说明

    (1)前置通知(Before advice):在某连接点(join point)之前执行的通知,但这个通知不能阻止连接点前的执行(除非它抛出一个异常)。

    (2)返回后通知(After returning advice):在某连接点(join point)正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。

    (3)抛出异常后通知(After throwing advice):在方法抛出异常退出时执行的通知。

    (4)后通知(After (finally) advice):当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。

    (5)环绕通知(Around Advice):包围一个连接点(join point)的通知,如方法调用。这是最强大的一种通知类型。 环绕通知可以在方法调用前后完成自定义的行为。它也会选择是否继续执行连接点或直接返回它们自己的返回值或抛出异常来结束执行。 环绕通知是最常用的一种通知类型。大部分基于拦截的AOP框架,例如Nanning和JBoss4,都只提供环绕通知。

    代码实现:

    配置文件

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置srping的Ioc,把service对象配置进来--> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean> <!-- 配置Logger类 --> <bean id="logger" class="com.itheima.utils.Logger"></bean> <!--配置AOP--> <aop:config> <!-- 配置切入点表达式 id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容 此标签写在aop:aspect标签内部只能当前切面使用。 它还可以写在aop:aspect外面,此时就变成了所有切面可用 --> <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut> <!--配置切面 --> <aop:aspect id="logAdvice" ref="logger"> <!-- 配置前置通知:在切入点方法执行之前执行--> <aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before> <!-- 配置后置通知:在切入点方法正常执行之后值。它和异常通知永远只能执行一个--> <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning> <!-- 配置异常通知:在切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个--> <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing> <!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行--> <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after> </aop:aspect> </aop:config> </beans>

    实现类

    /** * 账户的业务层实现类 */ public class AccountServiceImpl implements IAccountService{ public void saveAccount() { System.out.println("执行了保存"); // int i=1/0; } public void updateAccount(int i) { System.out.println("执行了更新"+i); } public int deleteAccount() { System.out.println("执行了删除"); return 0; } }

    日志类

    public class Logger { /** * 前置通知 */ public void beforePrintLog(){ System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。"); } /** * 后置通知 */ public void afterReturningPrintLog(){ System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。"); } /** * 异常通知 */ public void afterThrowingPrintLog(){ System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。"); } /** * 最终通知 */ public void afterPrintLog(){ System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。"); } }

    测试类

    public class AOPTest { public static void main(String[] args) { //1.获取容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.获取对象 IAccountService as = (IAccountService)ac.getBean("accountService"); //3.执行方法 as.saveAccount(); } }

    6.环绕通知

    1.步骤说明

    问题:当我们配置了环绕通知之后,切入点方法没执行,而通知方法执行了。

    分析:通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知明确的切入点方法调用,而我们的代码中没。

    解决:Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口一个方法proceed(),此方法就相当于明确调用切入点方法。 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。

    spring中的环绕通知: 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。

    2.代码实现:

    public class Logger { @Around("pt1()") public Object aroundPringLog(ProceedingJoinPoint pjp){ Object rtValue = null; try{ Object[] args = pjp.getArgs();//得到方法执行所需的参数 System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置"); rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法) System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置"); return rtValue; }catch (Throwable t){ System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常"); throw new RuntimeException(t); }finally { System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终"); } } }

    配置文件

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置srping的Ioc,把service对象配置进来--> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean> <!-- 配置Logger类 --> <bean id="logger" class="com.itheima.utils.Logger"></bean> <!--配置AOP--> <aop:config> <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut> <!--配置切面 --> <aop:aspect id="logAdvice" ref="logger"> <!-- 配置环绕通知 详细的注释请看Logger类中--> <!--<aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around>--> </aop:aspect> </aop:config> </beans>

    7.基于注解的配置

    1.步骤说明

    1.首先在配置文件里开启声明式aop注解支持 <!--开启声明式事务注解,对aop支持--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 2.在logging类上声明其为一个切面类 @Aspect //表示当前类是一个切面类 3.在类中声明一个方法作为切入点表达式 @Pointcut("execution(* com.itheima.service.impl.*.*(..))") //表示切入点 private void pt1(){ } 4.在各个方法上添加注解 @Component("logger") //表示把当前类放入spring容器中 @Before("pt1()") //表示前置通知,在方法执行之前执行 @AfterReturning("pt1()") //表示后置通知,在方法执行之后执行 @AfterRunning:返回通知,在方法返回结果之后执行 @AfterThrowing("pt1()") //表示异常通知,在方法抛出异常之后执行 @After("pt1()") //表示最终通知 @Around("pt1()") //表示环绕通知,围绕着方法执行 @Service("accountService") //表示当前类是一个业务层 5.设置切面优先级 @Order(2)//通过@Order(2)注解指定切面优先级,value值越小,优先级越高,默认是int最大值。 注解:(context名称空间和约束)

    2.代码实现:

    配置文件

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置spring创建容器时要扫描的包--> <context:component-scan base-package="com.itheima"></context:component-scan> <!-- 配置spring开启注解AOP的支持 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>

    日志类

    /** * 用于记录日志的工具类,它里面提供了公共的代码 */ @Component("logger") @Aspect//表示当前类是一个切面类 public class Logger { @Pointcut("execution(* com.itheima.service.impl.*.*(..))") private void pt1(){} /** * 前置通知 */ // @Before("pt1()") public void beforePrintLog(){ System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。"); } /** * 后置通知 */ // @AfterReturning("pt1()") public void afterReturningPrintLog(){ System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。"); } /** * 异常通知 */ // @AfterThrowing("pt1()") public void afterThrowingPrintLog(){ System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。"); } /** * 最终通知 */ // @After("pt1()") public void afterPrintLog(){ System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。"); } @Around("pt1()") public Object aroundPringLog(ProceedingJoinPoint pjp){ Object rtValue = null; try{ Object[] args = pjp.getArgs();//得到方法执行所需的参数 System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置"); rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法) System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置"); return rtValue; }catch (Throwable t){ System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常"); throw new RuntimeException(t); }finally { System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终"); } } }

    实现类

    /** * 账户的业务层实现类 */ @Service("accountService") public class AccountServiceImpl implements IAccountService{ public void saveAccount() { System.out.println("执行了保存"); int i=1/0; } public void updateAccount(int i) { System.out.println("执行了更新"+i); } public int deleteAccount() { System.out.println("执行了删除"); return 0; } }

    测试类

    /** * 测试AOP的配置 */ public class AOPTest { public static void main(String[] args) { //1.获取容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.获取对象 IAccountService as = (IAccountService)ac.getBean("accountService"); //3.执行方法 as.saveAccount(); } }

    链接: 对Spring深入的理解 | 概念的总结 链接: Spring IOC详解 链接: Spring 依赖注入详解 链接: Spring 事务详解


    如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发 创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
    Processed: 0.016, SQL: 9