Spring AOP - 配置文件方式实现

目录

AOP基础概念

示例1:模拟在com.text包及子包项下所有类名称以ServiceImpl结尾的类的所有方法执行前、执行后、执行正常后返回值、执行过程中出异常的情况

示例2:统计com.text包及子包项下所有类名称以DaoImpl结尾的类的所有方法执行时长情况


AOP基础概念

AOP:Aspect Oriented Programming 面向切面编程

使用场景:将一些通用的功能封装成切面类,切面类作用在目标类方法的前后,并通过自动插拔实现目标类方法的前后逻辑,示意图如下:

上述的示意图显示,Aspect切面类横向贯穿了3个目标类方法的执行逻辑之前,由此可以看出,AOP实现需要如下组件:

  1. 切面类(Aspect类)
  2. 切点(Pointcut),即上图的各个目标方法,通过切点表达式(execution)实现
  3. 连接点(JoinPoint) ,切面和切点之间的连接信息,可以理解为横切面和切点的交汇处
  4. 通知(Advice) ,在目标类方法的之前、之后还是环绕执行切面逻辑

Spring AOP实现需要引入aspectjweaver依赖

<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.6</version>
</dependency>

示例1:模拟在com.text包及子包项下所有类名称以ServiceImpl结尾的类的所有方法执行前、执行后、执行正常后返回值、执行过程中出异常的情况

1、配置文件:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"xmlns="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!--<context:component-scan base-package="com.text"/>--><bean id="studentService" class="com.text.service.impl.StudentServiceImpl"/><!-- 切面类交给IOC容器实例 --><bean id="methodAspect" class="com.text.aspect.MethodAspect"/><!-- aop配置--><aop:config><!-- 切点配置,expression表示com.text所有包及子包项下所有服务层(以ServiceImpl结束的类)的所有方法--><aop:pointcut id="pointcut" expression="execution(public * com.text..*ServiceImpl.*(..))"/><!-- 切面配置--><aop:aspect ref="methodAspect"><!-- 切点方法执行之前执行--><aop:before method="methodInvokeBefore" pointcut-ref="pointcut"/><!-- 切点方法执行之后执行--><aop:after method="methodInvokeAfter" pointcut-ref="pointcut"/><!-- 切点方法执行之后带返回值--><aop:after-returning method="methodInvokeAfterReturn" returning="ret" pointcut-ref="pointcut"/><!-- 切点方法执行时出现异常--><aop:after-throwing method="methodInvokeException" throwing="thr" pointcut-ref="pointcut"/></aop:aspect></aop:config></beans>

2、服务类及方法(pointcut)

package com.text.service.impl;import com.text.entity.Course;
import com.text.entity.Student;
import com.text.service.StudentService;public class StudentServiceImpl implements StudentService {@Overridepublic void save(Student student) {System.out.println(student + "正在被保存...");}@Overridepublic void deleteById(String id) {System.out.println("学生id=" + id + "的记录已被删除...");}@Overridepublic void updateById(String id) throws Exception{System.out.println("学生id=" + id + "的记录正在被修改...");throw new Exception("修改学生信息出异常");}@Overridepublic Student searchById(String id) {System.out.println("已查询到学生id=" + id + "的记录...");return new Student("张三",20,new Course("计算机"));}
}

3、切面类(aspect) 

package com.text.aspect;import org.aspectj.lang.JoinPoint;/*** 定义方法切面类*/
public class MethodAspect {public void methodInvokeBefore(JoinPoint joinPoint) {String targetClassName = joinPoint.getTarget().getClass().getName();//获取切面执行的目标类String methodName = joinPoint.getSignature().getName();System.out.println(targetClassName + "." + methodName + "方法执行之前的处理逻辑...");}public void methodInvokeAfter(JoinPoint joinPoint) {String targetClassName = joinPoint.getTarget().getClass().getName();//获取切面执行的目标类String methodName = joinPoint.getSignature().getName();System.out.println(targetClassName + "." + methodName + "方法执行之后的处理逻辑...");}public void methodInvokeAfterReturn(JoinPoint joinPoint,Object ret) {String targetClassName = joinPoint.getTarget().getClass().getName();//获取切面执行的目标类String methodName = joinPoint.getSignature().getName();System.out.println(targetClassName + "." + methodName + "方法执行之后返回的结果为:" + ret);}public void methodInvokeException(JoinPoint joinPoint,Throwable thr) throws Throwable {String targetClassName = joinPoint.getTarget().getClass().getName();//获取切面执行的目标类String methodName = joinPoint.getSignature().getName();System.out.println(targetClassName + "." + methodName + "方法执行中的异常信息为:" + thr.getMessage());throw thr;}
}

4、测试类 Application

package com.text;
import com.text.entity.Course;
import com.text.entity.Student;
import com.text.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Application {public static void main(String[] args) throws Exception {ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");StudentService studentService = context.getBean("studentService", StudentService.class);studentService.save(new Student("张三",20,new Course("计算机")));System.out.println("======save end========");studentService.deleteById("1");System.out.println("======delete end ========");Student student = studentService.searchById("1");System.out.println("======search end ========");studentService.updateById("1");System.out.println("======update end ========");}
}

5、输出结果:

示例2:统计com.text包及子包项下所有类名称以DaoImpl结尾的类的所有方法执行时长情况

此需求如果按照之前的advice至少需要写2个,一个是aop:before,一个是aop:after,方法的总执行时间需要after的当前时间减去before的当前时间,这2个时间如何联通也存在困难,AOP 提供一种自定义的通知执行时机-Around Advice(环绕通知)可以轻松解决此需求

1、配置文件:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"xmlns="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!--<context:component-scan base-package="com.text"/>--><bean id="studentDao" class="com.text.dao.impl.StudentDaoImpl"/><!-- 切面类交给IOC容器实例 --><bean id="methodAspect" class="com.text.aspect.MethodAspect"/><!-- aop配置--><aop:config><!-- 切点配置,expression表示com.text所有包及子包项下所有服务层(以DaoImpl结束的类)的所有方法--><aop:pointcut id="pointcut" expression="execution(public * com.text..*DaoImpl.*(..))"/><!-- 切面配置--><aop:aspect ref="methodAspect"><!-- 自定义的环绕通知--><aop:around method="countMethodInvokeTime" pointcut-ref="pointcut"/></aop:aspect></aop:config></beans>

2、服务类及方法(pointcut)

package com.text.dao.impl;
import com.text.dao.StudentDao;public class StudentDaoImpl implements StudentDao {@Overridepublic void getById(String id) throws Exception {Thread.sleep(1000);System.out.println("查询学生id=" + id + "的信息");}
}

3、切面类(aspect) 

package com.text.aspect;import org.aspectj.lang.ProceedingJoinPoint;import java.util.Date;/*** 定义方法切面类*/
public class MethodAspect {public void countMethodInvokeTime(ProceedingJoinPoint proceedingJoinPoint) {System.out.println("目标方法执行之前记录初始时间...");Date startTime = new Date();try {proceedingJoinPoint.proceed();//执行目标方法 即:StudentDaoImpl.getById方法System.out.println("目标方法执行之后记录结束时间...");String methodName = proceedingJoinPoint.getTarget().getClass().getName() + "." +proceedingJoinPoint.getSignature().getName();Date endTime = new Date();System.out.println(methodName + "方法执行总时长为:" + (endTime.getTime() - startTime.getTime()) + "毫秒");} catch (Throwable throwable) {throwable.printStackTrace();}}
}

4、测试类 Application

package com.text;import com.text.dao.StudentDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Application {public static void main(String[] args) throws Exception {ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");StudentDao studentDao = context.getBean("studentDao", StudentDao.class);studentDao.getById("1");System.out.println("======getById end========");}
}

5、输出结果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/147900.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

英伟达开源 NVLM 1.0 引领多模态 AI 变革

新闻 NVLM 1.0 是由英伟达&#xff08;Nvidia&#xff09;最新推出的一系列前沿级别的多模态大型语言模型&#xff08;MLLM&#xff09;&#xff0c;这些模型在视觉-语言任务上取得了与领先专有模型&#xff08;例如 GPT-4o&#xff09;和开放访问模型&#xff08;例如 Llama 3…

文件上传、重定向、Gin路由

文件上传 单个文件上传 index.html 文件上传前端页面代码&#xff1a; <!DOCTYPE html> <html lang"zh-CN"> <head><title>index</title> </head> <body> <form action"/upload" method"post"…

【WPF】桌面程序开发之窗口的用户控件详解

使用Visual Studio开发工具&#xff0c;我们可以编写在Windows系统上运行的桌面应用程序。其中&#xff0c;WPF&#xff08;Windows Presentation Foundation&#xff09;项目是一种常见的选择。然而&#xff0c;对于初学者来说&#xff0c;WPF项目中xaml页面的布局设计可能是一…

基础算法(4)——前缀和

1. 前缀和 题目描述&#xff1a; 解法一&#xff1a;暴力解法 直接模拟实现题目流程即可 时间复杂度为&#xff0c;根据题目给出的条件&#xff0c;肯定会超时 解法二&#xff1a;前缀和&#xff08;适用题型&#xff1a;快速 求出数组中某一个 连续区间 的 和&#xff09;…

车路云一体化大模型数据治理方案

车路云一体化大模型数据治理解决方案 "杭州市发改委已批复了杭州交通投资集团的智能网联汽车“车路云一体化”试点项目。这一批复体现了其对该项目可行性研究报告的肯定&#xff0c;预示着杭州市在智能驾驶领域的进一步发展。" 2024年6月18日&#xff0c;第十一届国…

WGS1984快速度确定平面坐标系UTM分带(快速套表、公式计算、软件范围判定)

之前我们介绍了坐标系3带6带快速确定带号及中央经线&#xff08;快速套表、公式计算、软件范围判定&#xff09;就&#xff0c;讲的是CGCS2000 高斯克吕格的投影坐标系。 那还有我们经常用的WGS1984的平面坐标系一般用什么投影呢? 对于全球全国的比如在线地图使用&#xff1a…

面向未来的算力网络连接发展趋势分析

面向未来的算力网络连接发展特点与实践 AI算力研究&#xff1a;英伟达B200再创算力奇迹&#xff0c;液冷、光模块持续革新 英伟达隆重宣布新一代Blackwell架构&#xff0c;华为对GPU算力需求高达百万片。 英伟达发布的GB200 NVL72 机架级系统内部包括 72 个 Blackwell GPU 和…

【排序算法】插入排序_直接插入排序、希尔排序

文章目录 直接插入排序直接插入排序的基本思想直接插入排序的过程插入排序算法的C代码举例分析插入排序的复杂度分析插入排序的优点 希尔排序希尔排序&#xff08;Shell Sort&#xff09;详解希尔排序的步骤&#xff1a;希尔排序的过程示例&#xff1a;希尔排序的C语言实现举例…

S3C2440定时器

ee一、构造 二、设置相关位 1、MPLLCON寄存器&#xff08;配置MPLL寄存器&#xff0c;进行倍频&#xff09; 根据下列表格的想要输出的频率进行选择&#xff0c;选择完毕之后&#xff0c;对该寄存器进行设置 2、时钟分频控制&#xff08;CLKDIVN&#xff09;寄存器 根据不…

CSP-J 2024 入门组初赛第一轮初赛试题及答案解析

CSP-J 2024 入门组初赛第一轮初赛试题及答案解析 一、 单项选择题&#xff08;共15题&#xff0c;每题2分&#xff0c;共计30分&#xff1a;每题有且仅有一个正确选项&#xff09; 1 32 位 int 类型的存储范围是&#xff08; &#xff09; A -2147483647 ~ 2147483647 B -21…

第十四章:html和css做一个心在跳动,为你而动的表白动画

💖 让心跳加速,传递爱意 💖 在这个特别的时刻,让爱在跳动中绽放!🌟 无论是初次相遇的心动,还是陪伴多年的默契,我们的心总在为彼此跳动。就像这颗炙热的爱心,随着每一次的跳动,传递着满满的温暖与期待。 在这个浪漫的季节,让我们一同感受爱的律动!无论你是在…

【深度学习】(4)--卷积神经网络

文章目录 卷积神经网络一、画面不变性二、图像识别三、卷积网络结构1. 原理2. 卷积层3. 池化层4. 全连接层 四、感受野 总结 卷积神经网络 卷积神经网络&#xff08;Convolutional Neural Network&#xff0c;简称CNN&#xff09;是一种深度学习模型&#xff0c;特别适用于处理…

基于SpringBoot+Vue+MySQL的校园一卡通系统

系统展示 用户前台界面 管理员后台界面 系统背景 随着现代社会的快速发展&#xff0c;校园一卡通已成为大学生活中不可或缺的一部分。它不仅承载着校园消费的功能&#xff0c;还集成了学生身份证明、图书馆借阅、门禁系统等多种服务。然而&#xff0c;传统的一卡通管理系统往往…

设计模式之策略模式例题

答案&#xff1a;A 知识点&#xff1a; 策略模式又叫模板方法模式 它的意图是定义一个操作中的算法骨架。而将一些步骤延迟到子类中&#xff0c;使得子类可以不改变一个算法的结构即可重新定义算法的某些特定步骤

Elasticsearch——介绍、安装与初步使用

目录 1.初识 Elasticsearch1.1.了解 ES1.1.1.Elasticsearch 的作用1.1.2.ELK技术栈1.1.3.Elasticsearch 和 Lucene1.1.4.为什么不是其他搜索技术&#xff1f;1.1.5.总结 1.2.倒排索引1.2.1.正向索引1.2.2.倒排索引1.2.3.正向和倒排 1.3.Elasticsearch 的一些概念1.3.1.文档和字…

大模型LLM对话模拟器Dialogue Simulator Visualization可视化工具

伴随着生成式人工智能技术发展&#xff0c;进2年涌现出大语言模型LLM/Agent系统/AI推理等众多方向的技术项目和论文。其中对话系统&#xff0c;智能体交互是用户通过UX界面和AI系统进行交互&#xff0c;这种交互有时候也是多模态&#xff08;用户输入文字/语音/图像&#xff09…

MySQL高阶1919-兴趣相同的朋友

题目 请写一段SQL查询获取到兴趣相同的朋友。用户 x 和 用户 y 是兴趣相同的朋友&#xff0c;需满足下述条件&#xff1a; 用户 x 和 y 是朋友&#xff0c;并且用户 x and y 在同一天内听过相同的歌曲&#xff0c;且数量大于等于三首. 结果表 无需排序 。注意&#xff1a;返…

用最通俗易懂的语言和例子讲解三维点云

前言&#xff1a; 我整体的学习顺序是看的按B站那“唯一”的三维点云的视频学习的&#xff08;翻了好久几乎没有第二个...&#xff09;对于深度学习部分&#xff0c;由于本人并没有进行学习&#xff0c;所以没有深究。大多数内容都进行了自己的理解并找了很多网络的资源方便理解…

论文阅读:A Generalization of Transformer Networks to Graphs

论文阅读&#xff1a;A Generalization of Transformer Networks to Graphs 1 摘要2 贡献Graph TransformerOn Graph Sparsity&#xff08;图稀疏&#xff09;On Positional Encodings&#xff08;位置编码&#xff09;3 Graph Transformer Architecture&#xff08;架构&#…

阿里HPN-用于大型语言模型训练的数据中心网络

阿里巴巴HPN:用于大型语言模型训练的数据中心网络 探索大规模语言模型训练新方法&#xff1a;阿里巴巴HPN数据中心网络论文。 摘要 本文介绍了阿里云用于大型语言模型(LLM)训练的数据中心网络HPN。由于LLM和一般云计算之间的差异(例如&#xff0c;在流量模式和容错性方面)&…