11.1、环境搭建

创建名为spring_aop_annotation的新module,过程参考9.1节

11.1.1、配置打包方式和依赖

注意:AOP需要在IOC的基础上实现,因此需要导入IOC的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>org.rain</groupId>
<artifactId>spring_aop_annotation</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging> <dependencies>
<!-- Spring-IOC的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency> <!-- spring-AOP的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.1</version>
</dependency> <!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies> </project>

11.1.2、创建Calculator接口及实现类

package org.rain.spring.aop.annotation;

/**
* @author liaojy
* @date 2023/8/12 - 17:43
*/
public interface Calculator { int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j); }

package org.rain.spring.aop.annotation;

import org.springframework.stereotype.Component;

/**
* @author liaojy
* @date 2023/8/12 - 17:45
*/ // @Component注解保证这个目标类能够放入IOC容器
@Component
public class CalculatorImpl implements Calculator {
public int add(int i, int j) { int result = i + j;
System.out.println("方法内部 result = " + result);
return result; } public int sub(int i, int j) { int result = i - j;
System.out.println("方法内部 result = " + result);
return result; } public int mul(int i, int j) { int result = i * j;
System.out.println("方法内部 result = " + result);
return result; } public int div(int i, int j) { int result = i / j;
System.out.println("方法内部 result = " + result);
return result; }
}

11.1.3、创建切面类LoggerAspect

package org.rain.spring.aop.annotation;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component; /**
* @author liaojy
* @date 2023/8/12 - 17:56
*/ // @Aspect表示这个类是一个切面类
@Aspect
// @Component注解保证这个切面类能够放入IOC容器
@Component
public class LoggerAspect {
}

11.1.4、创建spring配置文件

<?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:context="http://www.springframework.org/schema/context"
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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--
对指定的package进行扫描,将使用组件注解的类的对象(本示例是目标对象和切面对象),交给spring的ioc容器来管理
-->
<context:component-scan base-package="org.rain.spring.aop.annotation"></context:component-scan> <!--
开启基于注解的AOP功能,该功能会为目标对象自动生成代理
-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>

11.2、前置通知的使用

11.2.1、基本示例

11.2.1.1、配置前置方法

    /*
* @Before注解:用于将方法标识为前置通知(方法)
* @Before注解的value属性值为切入点表达式,其作用是将该前置通知(方法)安插到对应目标方法的连接点上
* */
@Before("execution(public int org.rain.spring.aop.annotation.CalculatorImpl.add(int , int))")
public void beforeMethod(){
System.out.println("LoggerAspect,前置通知");
}

11.2.1.2、测试使用效果

由控制台日志可知,切面类的前置通知(方法),通过切入点表达式,作用到了目标方法的连接点上

    @Test
public void testAOPByAnnotation(){ ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aop-annotation.xml"); // 注意:这里不能直接获取目标对象来使用;因为使用了AOP之后,IOC容器中就只有对应目标对象的代理对象;
// 如果强行获取目标对象,则报错:NoSuchBeanDefinitionException
//Calculator calculator = ioc.getBean(CalculatorImpl.class); // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class); // 只能通过代理对象来访问目标对象中的方法
calculator.add(1,2); }

11.2.2、高级示例

11.2.2.1、改进前置方法

该示例中(前置)通知方法引入了连接点参数,通过连接点参数,可以动态获取(切入点表达式)对应的目标方法的名称和参数列表

    /*
* @Before注解:用于将方法标识为前置通知(方法)
* @Before注解的value属性值为切入点表达式,其作用是将该前置通知(方法)安插到对应目标方法的连接点上
* */
@Before("execution(public int org.rain.spring.aop.annotation.CalculatorImpl.add(int , int))")
// joinPoint参数:可以获取(通过切入点表达式定位出的)连接点的相关信息
public void beforeMethod(JoinPoint joinPoint){
// 获取连接点所对应目标方法的名称
String methodName = joinPoint.getSignature().getName();
// 获取连接点所对应目标方法的参数列表
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->前置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
}

11.2.2.2、测试使用效果

11.3、切入点表达式的进阶用法

11.3.1、高频用法示例

    // @Before("execution(public int org.rain.spring.aop.annotation.CalculatorImpl.add(int , int))")

    /**
* 第一个*表示任意访问修饰符和返回值类型,
* 第二个*表示该类的任意方法名称,
* (..)表示方法的任意参数列表
* 在类的位置也可以使用*,表示当前包下所有的类,
* 在包的位置也可以使用*,表示当前包下所有的子包,
*/
@Before("execution(* org.rain.spring.aop.annotation.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->前置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
}

11.3.2、详细语法图解

11.3.3、复用切入点表达式

11.3.3.1、声明公共的切入点表达式

    @Pointcut("execution(* org.rain.spring.aop.annotation.CalculatorImpl.*(..))")
public void pointCutOne(){}

11.3.3.2、在同一个切面类中复用

    // @Before注解的value属性值,可以设置为使用了@Pointcut注解标识的方法名,从而复用该@Pointcut注解定义的切入点表达式
@Before("pointCutOne()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->前置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
}

11.3.3.3、在不同一个切面类中复用

    // 复用其他切面类中@Pointcut注解定义的切入点表达式,
// @Before注解的value属性值,需要设置为使用了@Pointcut注解标识的(全限定类名+)方法名
@Before("org.rain.spring.aop.annotation.LoggerAspect.pointCutOne()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->前置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
}

11.4、其他通知的使用

11.4.1、后置通知

11.4.1.1、配置后置方法

    // @After注解:用于将方法标识为后置通知(方法)
@After("pointCutOne()")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->后置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
}

11.4.1.2、测试使用效果

由控制台日志可知,后置通知在目标对象方法的finally子句中执行(一般用于释放资源)

    @Test
public void testAOPByAnnotation(){ ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aop-annotation.xml"); // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class); // 只能通过代理对象来访问目标对象中的方法
calculator.div(1,0); }

11.4.2、返回通知

11.4.2.1、配置返回通知

    /**
* @AfterReturning注解:用于将方法标识为返回通知(方法)
* returning属性:指定(返回)通知方法中的某个参数(名),用于接收目标对象方法的返回值
*/
@AfterReturning(value = "pointCutOne()",returning = "result")
public void afterReturningMethod(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->返回通知,方法名:"+methodName+",结果:"+ result);
}

11.4.2.2、测试使用效果

由控制台日志可知,返回通知在目标对象方法的返回值之后执行

    @Test
public void testAOPByAnnotation(){ ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aop-annotation.xml"); // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class); // 只能通过代理对象来访问目标对象中的方法
calculator.div(1,1); }

11.4.3、异常通知

11.4.3.1、配置异常通知

    /**
* @AfterThrowing注解:用于将方法标识为异常通知(方法)
* throwing属性:指定(异常)通知方法中的某个参数(名),用于接收目标对象方法出现的异常
*/
@AfterThrowing(value = "pointCutOne()",throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint,Exception ex){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect-->异常通知,方法名:"+methodName+",异常:"+ ex);
}

11.4.3.2、测试使用效果

由控制台日志可知,异常通知在目标对象方法的catch子句中执行

    @Test
public void testAOPByAnnotation(){ ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aop-annotation.xml"); // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class); // 只能通过代理对象来访问目标对象中的方法
calculator.div(1,0); }

11.4.4、通知的执行顺序

11.4.4.1、Spring版本5.3.x以前

  • 前置通知

  • 目标操作

  • 后置通知

  • 返回通知或异常通知

11.4.4.2、Spring版本5.3.x以后

本示例

  • 前置通知

  • 目标操作

  • 返回通知或异常通知

  • 后置通知

11.5、环绕通知

11.5.1、配置环绕通知

环绕通知和动态代理的形式,非常相似

    /**
* @Around注解:用于将方法标识为环绕通知(方法)
* 环绕通知(方法)使用的参数是ProceedingJoinPoint类型
* 环绕通知(方法)的返回值,必须和目标对象方法的返回值一致
*/
@Around("pointCutOne()")
public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){
String methodName = proceedingJoinPoint.getSignature().getName();
Object[] args = proceedingJoinPoint.getArgs();
Object result = null;
try {
System.out.println("LoggerAspect-->环绕前置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
// 表示目标对象方法的执行
result = proceedingJoinPoint.proceed();
System.out.println("LoggerAspect-->环绕返回通知,方法名:"+methodName+",结果:"+ result);
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("LoggerAspect-->环绕异常通知,方法名:"+methodName+",异常:"+ throwable);
}finally {
System.out.println("LoggerAspect-->环绕后置通知,方法名:"+methodName+",参数:"+ Arrays.toString(args));
}
return result;
}

11.5.2、测试使用效果

注意:因为环绕通知包括了其他四种通知,所以一般要么配置其他四种通知,要么只配置环绕通知;本示例为了展示效果才同时配置

    @Test
public void testAOPByAnnotation(){ ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aop-annotation.xml"); // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class); // 只能通过代理对象来访问目标对象中的方法
calculator.div(1,1); }

11.6、切面的优先级

11.6.1、创建其他切面类ValidateAspect

package org.rain.spring.aop.annotation;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component; /**
* @author liaojy
* @date 2023/8/15 - 7:49
*/
@Aspect
@Component
public class ValidateAspect {
}

11.6.2、配置前置通知方法

    @Before("org.rain.spring.aop.annotation.LoggerAspect.pointCutOne()")
public void beforeMethod(){
System.out.println("ValidateAspect-->前置通知");
}

11.6.3、测试使用效果

由控制台日志可知,ValidateAspect切面的前置通知方法生效了,但执行顺序在LoggerAspect切面的前置通知方法的后面

    @Test
public void testAOPByAnnotation(){ ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-aop-annotation.xml"); // 虽然不知道代理对象的类名,但可以通过代理对象和目标对象共同实现的接口类型来从ioc容器中获取代理对象
Calculator calculator = ioc.getBean(Calculator.class); // 只能通过代理对象来访问目标对象中的方法
calculator.div(1,1); }

11.6.4、调整切面的优先级

package org.rain.spring.aop.annotation;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; /**
* @author liaojy
* @date 2023/8/15 - 7:49
*/
@Aspect
@Component
// @Order注解:用于设置切面的优先级,value属性值越小,优先级越高,默认值为Integer的最大值
@Order(2023)
public class ValidateAspect { @Before("org.rain.spring.aop.annotation.LoggerAspect.pointCutOne()")
public void beforeMethod(){
System.out.println("ValidateAspect-->前置通知");
} }

11.6.5、测试调整后的效果

由控制台日志可知,ValidateAspect切面的前置通知方法的执行顺序,在LoggerAspect切面的前置通知方法的前面

这是因为ValidateAspect切面的@Order注解的value属性值已设为2023,要小于LoggerAspect切面所使用的默认值(Integer的最大值2147483647)

11.7、扩展知识

  • AspectJ本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,但最终效果是动态的。

  • weaver就是织入器,Spring只是借用了AspectJ中的注解。

11、Spring之基于注解的AOP的更多相关文章

  1. spring中基于注解使用AOP

    本文内容:spring中如何使用注解实现面向切面编程,以及如何使用自定义注解. 一个场景 比如用户登录,每个请求发起之前都会判断用户是否登录,如果每个请求都去判断一次,那就重复地做了很多事情,只要是有 ...

  2. Spring AspectJ基于注解的AOP实现

    对于AOP这种编程思想,很多框架都进行了实现.Spring就是其中之一,可以完成面向切面编程.然而,AspectJ也实现了AOP的功能,且实现方式更为简捷,使用更加方便,而且还支持注解式开发.所以,S ...

  3. Spring:基于注解的Spring MVC

    什么是Spring MVC Spring MVC框架是一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...

  4. Spring_Spring与AOP_AspectJ基于注解的AOP实现

    一.AspectJ.Spring与AOP的关系 AspectJ是一个面向切面的框架,它扩展了Java语言.AspectJ定义了AOP语法,所以它有一个专门的编译器用来生成遵守Java字节编码规范的Cl ...

  5. spring的基于xml的AOP配置案例和切入点表达式的一些写法

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr ...

  6. Spring boot 基于注解方式配置datasource

    Spring boot 基于注解方式配置datasource 编辑 ​ Xml配置 我们先来回顾下,使用xml配置数据源. 步骤: 先加载数据库相关配置文件; 配置数据源; 配置sqlSessionF ...

  7. Spring中基于xml的AOP

    1.Aop 全程是Aspect Oriented Programming 即面向切面编程,通过预编译方式和运行期动态代理实现程序功能的同一维护的一种技术.Aop是oop的延续,是软件开发中的 一个热点 ...

  8. Spring基础知识之基于注解的AOP

    背景概念: 1)横切关注点:散布在应用中多处的功能称为横切关注点 2)通知(Advice):切面完成的工作.通知定了了切面是什么及何时调用. 5中可以应用的通知: 前置通知(Before):在目标方法 ...

  9. 阶段3 2.Spring_08.面向切面编程 AOP_9 spring基于注解的AOP配置

    复制依赖和改jar包方式 src下的都复制过来. 复制到新项目里了 bean.xml里面复制上面一行代码到下面.把aop改成context. 配置spring容器创建时要扫描的包 Service的配置 ...

  10. Spring+Mybatis基于注解整合Redis

    基于这段时间折腾redis遇到了各种问题,想着整理一下.本文主要介绍基于Spring+Mybatis以注解的形式整合Redis.废话少说,进入正题. 首先准备Redis,我下的是Windows版,下载 ...

随机推荐

  1. Django笔记四十之运行Django环境的python脚本

    本文首发于公众号:Hunter后端 原文链接:Django笔记四十之运行Django环境的python脚本 这一篇笔记介绍如何在 Django 中运行脚本. 假设说我们要实现一个功能,需要获取 blo ...

  2. Can't uninstall 'Pillow'. No files were found to uninstall.

    Can't uninstall 'Pillow'. No files were found to uninstall. Pillow卸载不掉的解决办法 1.进入python所在路径,进入scripts ...

  3. Flutter编写的数独游戏

    一个使用Flutter编写的每日数独小游戏,支持Android和ios.代码已上传到github:https://github.com/huhx/flutter_sudoku Library 状态管理 ...

  4. 【工作随手记】deaklock排查

    生产环境当中还没真正遇到过死锁的问题.有些疑似死锁的问题,后来经过排查也只是其它问题导致的.所以通过jstack到底怎样排查死锁问题有点疏忽了.这里作个记录. 模拟一个死锁 顺便复习一下. 死锁的产生 ...

  5. flutter系列之:做一个下载按钮的动画

    目录 简介 定义下载的状态 定义DownloadButton的属性 让DownloadButton的属性可以动态变化 定义downloadController 定义DownloadButton的细节 ...

  6. Linux 调用约定

      函数调用约定是对函数调用时如何传递参数的一种约定.关于它的约定有许多种,下面我们分 别从内核接口和用户接口两方面介绍32位和64位Linux的调用约定. 一.内核接口   x86-32系统调用约定 ...

  7. To ChatGPT:让你更加随意地使用所有ChatGPT应用

    现在其实已经有很多在线的llm服务了,当然也存在许多开源部署方案,但是不知道大家有没有发现一个问题,目前基于ChatGPT开发的应用,都是使用的OpenAI的接口.换句话说,如果没有OpenAI账号, ...

  8. 深度解析SpringBoot内嵌Web容器

    你好,我是刘牌! 前言 今天分享一个SpringBoot的内嵌Web容器,在SpringBoot还没有出现时,我们使用Java开发了Web项目,需要将其部署到Tomcat下面,需要配置很多xml文件, ...

  9. Windows服务启动exe无界面终极解决方案

      1.前言 我这个方案(C#操作)是彻底解决[从Windows服务启动程序exe,程序无界面]问题的终极解决方案,终极方案,绝对的终极方案,本来打算收钱的,还是算了,你们也不容易,关注我一下就行.后 ...

  10. WPF复习知识点记录

    WPF复习知识点记录 由于近几年主要在做Web项目,客户端的项目主要是以维护为主,感觉对于基础知识的掌握没有那么牢靠,趁着这个周末重新复习下WPF的相关知识. 文章内容主要来自大佬刘铁锰老师的经典著作 ...