Spring之AOP的特性

news/2025/2/5 20:42:46/

一. AOP简介

AOP是Aspect-Oriented Programming的缩写,即面向切面编程。利用oop思想,可以很好的处理业务流程,但是不能把系统中某些特定的重复性行为封装到模块中。例如,在很多业务中都需要记录操作日志,结果我们不得不在业务流程中嵌入大量的日志记录代码。无论是对业务代码还是对日志记录代码来说,维护都是相当复杂的。由于系统中嵌入了这种大量的与业务无关的其他重复性代码,系统的复杂性、代码的重复性增加了。维护起来会更加复杂。

AOP可以很好解决这个问题,AOP关注的是系统的“截面”,在适当的时候“拦截”程序的执行流程,把程序的预处理和后期处理交给某个拦截器来完成。比如,访问数据库时需要记录日志,如果使用AOP的编程思想,那么在处理业务流程时不必在去考虑记录日志,而是把它交给一个专门的例子记录模块去完成。这样,程序员就可以集中精力去处理业务流程,而不是在实现业务代码时嵌入日志记录代码,实现业务代码与非业务代码的分别维护。在AOP术语中,这称为关注点分离。AOP的常见应用有日志拦截、授权认证、数据库的事务拦截和数据审计等。

当一个方法,对不同的用户的功能要求不满足时,那么需要在此方法的地方就可以出现变化;在这个变化点进行封转,留下一个可扩展的接口,便于后期的维护;
简单来说就是, 将非业务核心代码进行封装

二. AOP中的关键性概念

连接点(Joinpoint):程序执行过程中明确的点,如方法的调用,或者异常的抛出.

目标(Target):被通知(被代理)的对象
注1:完成具体的业务逻辑

通知(Advice):在某个特定的连接点上执行的动作,同时Advice也是程序代码的具体实现,例如一个实现日志记录的代码(通知有些书上也称为处理)
注2:完成切面编程

代理(Proxy):将通知应用到目标对象后创建的对象(代理=目标+通知),
例子:外科医生+护士
注3:只有代理对象才有AOP功能,而AOP的代码是写在通知的方法里面的

切入点(Pointcut):多个连接点的集合,定义了通知应该应用到那些连接点。
(也将Pointcut理解成一个条件 ,此条件决定了容器在什么情况下将通知和目标组合成代理返回给外部程序)

适配器(Advisor):适配器=通知(Advice)+切入点(Pointcut)

在 Spring 中 AOP 代理使用 JDK 动态代理和 CGLIB 代理来实现,默认如果目标对象是接口,则使用 JDK 动态代理,否则使用 CGLIB 来生成代理类。

三. 前置通知

前置通知(org.springframework.aop.MethodBeforeAdvice):在连接点之前执行的通知()
目标接口

package com.xissl.aop.biz;public interface IBookBiz {// 购书public boolean buy(String userName, String bookName, Double price);// 发表书评public void comment(String userName, String comments);
}

接口实现类

package com.xissl.aop.biz.impl;import com.xissl.aop.biz.IBookBiz;
import com.xissl.aop.exception.PriceException;public class BookBizImpl implements IBookBiz {public BookBizImpl() {super();}public boolean buy(String userName, String bookName, Double price) {// 通过控制台的输出方式模拟购书if (null == price || price <= 0) {throw new PriceException("book price exception");}System.out.println(userName + " buy " + bookName + ", spend " + price);return true;}public void comment(String userName, String comments) {// 通过控制台的输出方式模拟发表书评System.out.println(userName + " say:" + comments);}}

通知

package com.xissl.aop.advice;import java.lang.reflect.Method;
import java.util.Arrays;import org.springframework.aop.MethodBeforeAdvice;/*** 买书、评论前加系统日志* @author xissl**/
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {@Overridepublic void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
//		在这里,可以获取到目标类的全路径及方法及方法参数,然后就可以将他们写到日志表里去String target = arg2.getClass().getName();String methodName = arg0.getName();String args = Arrays.toString(arg1);System.out.println("【前置通知:系统日志】:"+target+"."+methodName+"("+args+")被调用了");}}

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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- aop--><!-- 目标对象--><bean class="com.xissl.aop.biz.impl.BookBizImpl" id="bookBiz"></bean><!-- 通知--><bean class="com.xissl.aop.advice.MyMethodBeforeAdvice" id="methodBeforeAdvice"></bean><!-- 代理--><bean class="org.springframework.aop.framework.ProxyFactoryBean" id="bookProxy"><!-- 配置目标对象--><property name="target" ref="bookBiz"></property>
<!--      配置代理的接口,目标对象的接口  --><property name="proxyInterfaces"><list><value>com.xissl.aop.biz.IBookBiz</value></list></property>
<!--        配置通知--><property name="interceptorNames"><list><value>methodBeforeAdvice</value></list></property></bean>
</beans>

工具类org.springframework.aop.framework.ProxyFactoryBean用来创建一个代理对象,在一般情况下它需要注入以下三个属性:
proxyInterfaces:代理应该实现的接口列表(List)
interceptorNames:需要应用到目标对象上的通知Bean的名字。(List)
target:目标对象 (Object)

测试

package com.xissl.aop.demo;import com.xissl.aop.biz.IBookBiz;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Demo01 {public static void main(String[] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
//        IBookBiz bookBiz = (IBookBiz) context.getBean("bookBiz");IBookBiz bookBiz = (IBookBiz) context.getBean("bookProxy");bookBiz.buy("yhsb","《大话西游》",39.9d);bookBiz.comment("yhsb","尊嘟好看");}
}

运行结果:
在这里插入图片描述

四. 后置通知

后置通知(org.springframework.aop.AfterReturningAdvice):在连接点正常完成后执行的通知
通知

package com.xissl.aop.advice;import java.lang.reflect.Method;
import java.util.Arrays;import org.springframework.aop.AfterReturningAdvice;/*** 买书返利* @author xissl**/
public class MyAfterReturningAdvice implements AfterReturningAdvice {@Overridepublic void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {String target = arg3.getClass().getName();String methodName = arg1.getName();String args = Arrays.toString(arg2);System.out.println("【后置通知:买书返利】:"+target+"."+methodName+"("+args+")被调用了,"+"该方法被调用后的返回值为:"+arg0);}}

配置到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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- aop--><!-- 目标对象--><bean class="com.xissl.aop.biz.impl.BookBizImpl" id="bookBiz"></bean><!-- 前置通知--><bean class="com.xissl.aop.advice.MyMethodBeforeAdvice" id="methodBeforeAdvice"></bean>
<!--    后置通知--><bean class="com.xissl.aop.advice.MyAfterReturningAdvice" id="myAfterReturningAdvice"></bean><!-- 代理--><bean class="org.springframework.aop.framework.ProxyFactoryBean" id="bookProxy"><!-- 配置目标对象--><property name="target" ref="bookBiz"></property>
<!--      配置代理的接口,目标对象的接口  --><property name="proxyInterfaces"><list><value>com.xissl.aop.biz.IBookBiz</value></list></property>
<!--        配置通知--><property name="interceptorNames"><list><value>methodBeforeAdvice</value><!-- 前置通知--><value>myAfterReturningAdvice</value><!-- 后置通知--></list></property></bean>
</beans>

运行结果:

在这里插入图片描述

五. 环绕通知

环绕通知(org.aopalliance.intercept.MethodInterceptor):包围一个连接点的通知,最大特点是可以修改返回值,由于它在方法前后都加入了自己的逻辑代码,因此功能异常强大。它通过MethodInvocation.proceed()来调用目标方法(甚至可以不调用,这样目标方法就不会执行)
通知

package com.xissl.aop.advice;import java.util.Arrays;import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;/*** 环绕通知* 	包含了前置和后置通知* * @author xissl**/
public class MyMethodInterceptor implements MethodInterceptor {@Overridepublic Object invoke(MethodInvocation arg0) throws Throwable {String target = arg0.getThis().getClass().getName();String methodName = arg0.getMethod().getName();String args = Arrays.toString(arg0.getArguments());System.out.println("【环绕通知调用前:】:"+target+"."+methodName+"("+args+")被调用了");
//		arg0.proceed()就是目标对象的方法Object proceed = arg0.proceed();System.out.println("【环绕通知调用后:】:该方法被调用后的返回值为:"+proceed);return proceed;}}

配置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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- aop--><!-- 目标对象--><bean class="com.xissl.aop.biz.impl.BookBizImpl" id="bookBiz"></bean><!-- 前置通知--><bean class="com.xissl.aop.advice.MyMethodBeforeAdvice" id="methodBeforeAdvice"></bean>
<!--    后置通知--><bean class="com.xissl.aop.advice.MyAfterReturningAdvice" id="myAfterReturningAdvice"></bean>
<!--    环绕通知--><bean class="com.xissl.aop.advice.MyMethodInterceptor" id="myMethodInterceptor"></bean><!-- 代理--><bean class="org.springframework.aop.framework.ProxyFactoryBean" id="bookProxy"><!-- 配置目标对象--><property name="target" ref="bookBiz"></property>
<!--      配置代理的接口,目标对象的接口  --><property name="proxyInterfaces"><list><value>com.xissl.aop.biz.IBookBiz</value></list></property>
<!--        配置通知--><property name="interceptorNames"><list><value>methodBeforeAdvice</value><!-- 前置通知--><value>myAfterReturningAdvice</value><!-- 后置通知--><value>myMethodInterceptor</value><!-- 环绕通知--></list></property></bean>
</beans>

运行结果:
在这里插入图片描述

六. 异常通知

异常通知(org.springframework.aop.ThrowsAdvice):这个通知会在方法抛出异常退出时执行
通知

package com.xissl.aop.advice;import org.springframework.aop.ThrowsAdvice;import com.xissl.aop.exception.PriceException;/*** 出现异常执行系统提示,然后进行处理。价格异常为例* @author xissl**/
public class MyThrowsAdvice implements ThrowsAdvice {public void afterThrowing(PriceException ex) {System.out.println("【异常通知】:当价格发生异常,那么执行此处代码块!!!");}
}

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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- aop--><!-- 目标对象--><bean class="com.xissl.aop.biz.impl.BookBizImpl" id="bookBiz"></bean><!-- 前置通知--><bean class="com.xissl.aop.advice.MyMethodBeforeAdvice" id="methodBeforeAdvice"></bean>
<!--    后置通知--><bean class="com.xissl.aop.advice.MyAfterReturningAdvice" id="myAfterReturningAdvice"></bean>
<!--    环绕通知--><bean class="com.xissl.aop.advice.MyMethodInterceptor" id="myMethodInterceptor"></bean>
<!--    异常通知--><bean class="com.xissl.aop.advice.MyThrowsAdvice" id="myThrowsAdvice"></bean><!-- 代理--><bean class="org.springframework.aop.framework.ProxyFactoryBean" id="bookProxy"><!-- 配置目标对象--><property name="target" ref="bookBiz"></property>
<!--      配置代理的接口,目标对象的接口  --><property name="proxyInterfaces"><list><value>com.xissl.aop.biz.IBookBiz</value></list></property>
<!--        配置通知--><property name="interceptorNames"><list><value>methodBeforeAdvice</value><!-- 前置通知--><value>myAfterReturningAdvice</value><!-- 后置通知--><value>myMethodInterceptor</value><!-- 环绕通知--><value>myThrowsAdvice</value><!-- 异常通知--></list></property></bean>
</beans>

测试

package com.xissl.aop.demo;import com.xissl.aop.biz.IBookBiz;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Demo01 {public static void main(String[] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
//        IBookBiz bookBiz = (IBookBiz) context.getBean("bookBiz");IBookBiz bookBiz = (IBookBiz) context.getBean("bookProxy");bookBiz.buy("yhsb","《大话西游》",-39.9d);bookBiz.comment("yhsb","尊嘟好看");}
}

运行结果:
在这里插入图片描述

七. 过滤通知

过滤后置通知的重复
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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- aop--><!-- 目标对象--><bean class="com.xissl.aop.biz.impl.BookBizImpl" id="bookBiz"></bean><!-- 前置通知--><bean class="com.xissl.aop.advice.MyMethodBeforeAdvice" id="methodBeforeAdvice"></bean>
<!--    后置通知--><bean class="com.xissl.aop.advice.MyAfterReturningAdvice" id="myAfterReturningAdvice"></bean>
<!--    环绕通知--><bean class="com.xissl.aop.advice.MyMethodInterceptor" id="myMethodInterceptor"></bean>
<!--    异常通知--><bean class="com.xissl.aop.advice.MyThrowsAdvice" id="myThrowsAdvice"></bean>
<!--    过滤通知--><bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" id="methodPointcutAdvisor"><property name="advice" ref="myAfterReturningAdvice"></property><property name="pattern" value=".*buy"></property></bean><!-- 代理--><bean class="org.springframework.aop.framework.ProxyFactoryBean" id="bookProxy"><!-- 配置目标对象--><property name="target" ref="bookBiz"></property>
<!--      配置代理的接口,目标对象的接口  --><property name="proxyInterfaces"><list><value>com.xissl.aop.biz.IBookBiz</value></list></property>
<!--        配置通知--><property name="interceptorNames"><list><value>methodBeforeAdvice</value><!-- 前置通知-->
<!--                <value>myAfterReturningAdvice</value>&lt;!&ndash; 后置通知&ndash;&gt;--><value>myMethodInterceptor</value><!-- 环绕通知--><value>myThrowsAdvice</value><!-- 异常通知--><value>methodPointcutAdvisor</value><!-- 过滤通知--></list></property></bean>
</beans>

运行结果:
在这里插入图片描述


http://www.ppmy.cn/news/1038964.html

相关文章

OSM模型案例:以游戏陪练app为例

OSM模型的概念 O指目标Objective&#xff1a;整个业务、乃至局部的小功能 能解决什么问题&#xff0c;提供什么样的用户价值&#xff0c;满足用户什么需求&#xff1f; S指策略Strategy&#xff1a;如何达成目标&#xff0c;以什么方式达成目标&#xff1f; M指度量Measure&…

kotlin字符串方法

以下是一些常用的 String 方法示例&#xff1a; 1.获取字符串长度&#xff1a; val str "Hello, Kotlin" val length str.length2.字符串比较&#xff1a; val str1 "apple" val str2 "banana" val compareResult str1.compareTo(str2) …

网页设计详解(一)-HTML简介

本文作为博主学习笔记&#xff1a;2023-05-04星期四 一、网页介绍 网页是构成网站的基本元素&#xff0c;它是一个包含HTML标签的纯文本文件&#xff0c;是超文本标记语言格式(文件扩展名为.html或.htm)。网页通常用图像档来提供图画&#xff0c;通过浏览器来阅读。 超文本介…

基于IMX6ULLmini的linux裸机开发系列一:汇编点亮LED

思来想去还是决定记录一下点灯&#xff0c;毕竟万物皆点灯嘛 编程步骤 使能GPIO时钟 设置引脚复用为GPIO 设置引脚属性(上下拉、速率、驱动能力) 控制GPIO引脚输出高低电平 使能GPIO时钟 其实和32差不多 先找到控制LED灯的引脚&#xff0c;也就是原理图 文件名 C:/Us…

vue2watch与vue3watch的区别

vue2watch与vue3watch的区别&#xff1f; Vue 2的watch&#xff1a; 在Vue 2中&#xff0c;可以使用watch选项或$watch方法来创建一个监听器。 watch选项用于定义一个或多个被监听的数据&#xff0c;并指定一个处理函数来响应数据变化。watch选项的写法比较灵活&#xff0c;可…

运行软件mfc140u.dll丢失怎么办?mfc140u.dll的三个修复方法

最近我在使用一款软件时遇到了一个问题&#xff0c;提示缺少mfc140u.dll文件。。这个文件是我在使用某个应用程序时所需要的&#xff0c;但是由于某种原因&#xff0c;它变得无法正常使用了。经过一番搜索和了解&#xff0c;我了解到mfc140u.dll是Microsoft Visual Studio 2015…

Linux 内核内存pfn相关函数

文章目录 一、 pfn简介二、pfn相关API2.1 pfn 与 PHYS2.2 pfn与 struct page2.3 pfn 与 virt2.4 pfn 与 node2.5 pfn其他函数 参考资料 一、 pfn简介 物理内存以页面为单位管理内存&#xff0c;这些物理内存称为物理页面或者页帧&#xff0c;操作系统为了管理这些物理页面&…

Effective C++学习笔记(8)

目录 条款49&#xff1a;了解new-handler的行为条款50&#xff1a;了解new和delete的合理替换时机条款51&#xff1a;编写new和delete时需固守常规条款52&#xff1a;写了placement new也要写placement delete条款53&#xff1a;不要轻忽编译器的警告条款54&#xff1a;让自己熟…