Spring AOP

本文介绍了Spring AOP(面向切面编程)的基本概念,它作为OOP的补充,用于解耦非业务代码。通过一个计算器的例子展示了如何使用动态代理实现AOP,然后详细阐述了Spring AOP的开发步骤,包括创建切面类、定义通知以及配置Spring XML。此外,还解释了AOP的相关术语,如切面对象、通知和连接点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring AOP

AOP(Aspect Oriented Programming)面向切面编程。
OOP(Object Oriented Programming)面向对象编程,用对象化的思想来完成程序。
AOP 是对 OOP 的⼀个补充,是在另外⼀个维度上抽象出对象。具体是指程序运行时动态地将非业务代码切⼊到业务代码中,从而实现程序的解耦合,将非业务代码抽象成⼀个对象,对对象编程就是面向切面编程。
在这里插入图片描述
上述形式的代码维护性差,没有代码复用性,使⽤ AOP 进行优化,如下图所示。
在这里插入图片描述
AOP 的优点:
1、可以降低模块之间的耦合性
2、提高代码的复用性
3、提高代码的维护性
4、集中管理非业务代码,便于维护
5、业务代码不受非业务代码的影响,逻辑更加清晰

通过⼀个例子来理解 AOP。
1、创建⼀个计算器接⼝ Cal

package com.southwind.aop;
public interface Cal {
 public int add(int num1,int num2);
 public int sub(int num1,int num2);
 public int mul(int num1,int num2);
 public int div(int num1,int num2);
}

2、创建接⼝的实现类 CalImpl

package com.southwind.aop.impl;
import com.southwind.aop.Cal;
public class CalImpl implements Cal {
 @Override
 public int add(int num1, int num2) {
 int result = num1 + num2;
 return result;
 }
 @Override
 public int sub(int num1, int num2) {
 int result = num1 - num2;
 return result;
 }
 @Override
 public int mul(int num1, int num2) {
 int result = num1 * num2;
 return result;
 }
 @Override
 public int div(int num1, int num2) {
 int result = num1 / num2;
 return result;
 }
}

日志打印
在每个方法开始位置输出参数信息。
在每个方法结束位置输出结果信息。

对于计算器来讲,加减乘除就是业务代码,⽇志打印就是非业务代码。
AOP 如何实现?使用动态代理的⽅式来实现。
代理首先应该具备 CalImpl 的所有功能,并在此基础上,扩展出打印日志的功能。
1、删除 CalImpl 方法中所有打印日志的代码,只保留业务代码。
2、创建 MyInvocationHandler 类,实现 InvocationHandler 接口,生成动态代理类。
动态代理类,需要动态生成,需要获取到委托类的接口信息,根据这些接口信息动态生成⼀个代理类,然后再由 ClassLoader 将动态生成的代理类加载到 JVM。

package com.southwind.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class MyInvocationHandler implements InvocationHandler {
 //委托对象
 private Object object = null;
 //返回代理对象
 public Object bind(Object object){
 this.object = object;
 return Proxy.newProxyInstance(
 object.getClass().getClassLoader(),
 object.getClass().getInterfaces(),
 this);
 }
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable {
 //实现业务代码和⾮业务代码的解耦合
 System.out.println(method.getName()+"⽅法的参数是"+
Arrays.toString(args));
 Object result = method.invoke(this.object,args);
 System.out.println(method.getName()+"⽅法的结果是"+ result);
 return result;
 }
}
package com.southwind.aop;
import com.southwind.aop.impl.CalImpl;
public class Test {
 public static void main(String[] args) {
 //实例化委托对象
 Cal cal = new CalImpl();
 //获取代理对象
 MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
 Cal proxy = (Cal) myInvocationHandler.bind(cal);
 proxy.add(10,3);
 proxy.sub(10,3);
 proxy.mul(10,3);
 proxy.div(10,3);
 }
}

上述代码通过动态代理机制实现了业务代码和非业务代码的解耦合,这是 Spring AOP 的底层实现机制,真正在使⽤ Spring AOP 进⾏开发时,不需要这么复杂,可以用更好理解的方式来完成开发。

Spring AOP 的开发步骤
在这里插入图片描述
1、创建切面类。

package com.southwind.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
public class LoggerAspect {
 @Before("execution(public int com.southwind.aop.impl.CalImpl.*(..))")
 public void before(JoinPoint joinPoint){
 String name = joinPoint.getSignature().getName();
 String args = Arrays.toString(joinPoint.getArgs());
 System.out.println(name+"⽅法的参数是"+args);
 }
 @After("execution(public int com.southwind.aop.impl.CalImpl.*(..))")
 public void after(JoinPoint joinPoint){
 String name = joinPoint.getSignature().getName();
 System.out.println(name+"⽅法执⾏完毕");
 }
 @AfterReturning(value = "execution(public int
com.southwind.aop.impl.CalImpl.*(..))",returning = "result")
 public void afterReturn(JoinPoint joinPoint,Object result){
 String name = joinPoint.getSignature().getName();
 System.out.println(name+"⽅法的结果是"+result);
 }
 @AfterThrowing(value = "execution(public int
com.southwind.aop.impl.CalImpl.*(..))",throwing = "ex")
 public void afterThrowing(JoinPoint joinPoint,Exception ex){
 String name = joinPoint.getSignature().getName();
 System.out.println(name+"⽅法抛出异常"+ex);
 }
}

@Component,将切面类加载到 IoC 容器中。

@Aspect,表示该类是⼀个切面类。

@Before,表示方法的执行时机是在业务方法之前,execution 表达式表示切⼊点是 CalImpl 类中的 add 方法。

@After,表示方法的执⾏时机是在业务⽅法结束之后,execution 表达式表示切⼊点是 CalImpl 类中的 add 方法。

@AfterReturning,表示方法的执行时机是在业务方法返回结果之后,execution 表达式表示切入点是 CalImpl 类中的 add 方法,returning 是将业务⽅法的返回值与切面类方法的形参进行绑定。

@AfterThrowing,表示方法的执行时机是在业务方法抛出异常之后,execution 表达式表示切入点是 CalImpl 类中的 add 方法,throwing 是将业务方法的异常与切面类方法的形参进行绑定。

2、委托类也需要添加 @Component

package com.southwind.aop.impl;
import com.southwind.aop.Cal;
import org.springframework.stereotype.Component;
@Component
public class CalImpl implements Cal {
 @Override
 public int add(int num1, int num2) {
 int result = num1 + num2;
 return result;
 }
 @Override
 public int sub(int num1, int num2) {
 int result = num1 - num2;
 return result;
 }
 @Override
 public int mul(int num1, int num2) {
 int result = num1 * num2;
 return result;
 }
 @Override
 public int div(int num1, int num2) {
 int result = num1 / num2;
 return result;
 }
}

3、spring.xml

<?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"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
 http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
 http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
">
 <!-- ⾃动扫包 -->
 <context:component-scan base-package="com.southwind.aop">
</context:component-scan>
 <!-- 为委托对象⾃动⽣成代理对象 -->
 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

aop:aspectj-autoproxy,Spring IoC 容器会结合切面对象和委托对象自动生成动态代理对象,AOP 底层就是通过动态代理机制来实现的。

AOP 的概念:
切面对象:根据切面抽象出来的对象,CalImpl 所有方法中需要加⼊日志的部分,抽象成⼀个切面类 LoggerAspect。
通知:切⾯对象具体执⾏的代码,即非业务代码,LoggerAspect 对象打印日志的代码。
目标:被横切的对象,即 CalImpl,将通知加⼊其中。
代理:切面对象、通知、⽬标混合之后的结果,即我们使⽤用JDK 动态代理机制创建的对象。
连接点:需要被横切的位置,即通知要插⼊业务代码的具体位置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

走不尽的心路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值