Spring AOP - 配置文件方式实现

server/2024/9/23 4:51:06/

目录

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)

java">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) 

java">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

java">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)

java">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) 

java">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

java">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.ppmy.cn/server/120633.html

相关文章

利用JAVA写一张纸折叠珠穆拉玛峰高度

public class zhumulama {public static void main(String[] args) {double height 8848860;double zhi 0.1;int count 0;while(zhi < height){zhi*2;//每次折完厚度count;//计数}System.out.println("一共需要折"count"次");System.out.println(&qu…

机器学习查漏补缺(4)

[M] What happens if we accidentally duplicate every data point in your train set or in your test set? Train set duplication: Duplicating every data point in the training set will effectively double the importance of each sample, but it won’t introduce ne…

laravel public 目录获取

在Laravel框架中&#xff0c;public目录是用来存放公共资源的&#xff0c;如CSS、JS、图片等。你可以通过多种方式获取public目录的路径。 方法一&#xff1a;使用helper函数public_path() $path public_path(); 方法二&#xff1a;使用Request类 $path Request::root().…

centos远程桌面连接windows

CentOS是一款广泛使用的Linux发行版&#xff0c;特别是在服务器领域。很多企业和个人用户会选择远程连接到CentOS进行操作和维护。虽然CentOS自带了一些远程桌面解决方案&#xff0c;但它们在使用上存在一些局限性。接下来&#xff0c;我将介绍如何实现CentOS的远程桌面连接&am…

【C++ Primer Plus习题】16.8

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream> #include <set> #includ…

华为HarmonyOS地图服务 1 -- 如何实现地图呈现?

如何使用地图组件MapComponent和MapComponentController呈现地图&#xff0c;效果如下图所示。 MapComponent是地图组件&#xff0c;用于在您的页面中放置地图。MapComponentController是地图组件的主要功能入口类&#xff0c;用来操作地图&#xff0c;与地图有关的所有方法从此…

Python练习宝典:Day 1 - 选择题 - 基础知识

目录 一、踏上Python之旅二、Python语言基础三、流程控制语句四、序列的应用 一、踏上Python之旅 1.想要输出 I Love Python,应该使用()函数。 A.printf() B.print() C.println() D.Print()2.Python安装成功的标志是在控制台(终端)输入python/python3后,命令提示符变为: A.&…

C语言6大常用标准库 -- 4.<math.h>

目录 引言 4. C标准库--math.h 4.1 简介 4.2 库变量 4.3 库宏 4.4 库函数 4.5 常用的数学常量 &#x1f308;你好呀&#xff01;我是 程序猿 &#x1f30c; 2024感谢你的陪伴与支持 ~ &#x1f680; 欢迎一起踏上探险之旅&#xff0c;挖掘无限可能&#xff0c;共同成长&…