Spring 4.x——AOP

本文深入探讨了AOP(面向切面编程)的概念与优势,详细解析了AspectJ注解在Spring框架中的应用,包括如何声明切面、定义通知以及使用切入点表达式。并通过示例展示了AspectJ在实际项目中的具体实现。

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

1.简介

        AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方法论是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充。AOP 的主要编程对象是切面(aspect), 切面模块化横切关注点。在应用 AOP 编程时, 仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且不必修改受影响的类这样一来横切关注点就被模块化到特殊的对象(切面)

AOP 的优点:

       (1)每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级。

       (2)业务模块更简洁, 只包含核心业务代码。

2.基本概念

       (1)切面(Aspect):  横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象

       (2)通知(Advice):  切面必须要完成的工作

       (3)目标(Target): 被通知的对象

       (4)代理(Proxy): 向目标对象应用通知之后创建的对象

       (5)连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。

       (6)切点(pointcut):每个类都拥有多个连接点:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件

3.AspectJ 注解

        (1)AspectJJava 社区里最完整最流行的 AOP 框架。(重要)

        (2)Spring2.0 以上版本, 可以使用基于 AspectJ 注解或基于 XML 配置的 AOP。

        (3)要在 Spring 应用中使用 AspectJ 注解, 必须在 classpath 下包含 AspectJ 类库: aop.jaraopalliance.jaraspectj.weaver.jar spring-aspects.jar。

        (4)aop Schema 添加到 <beans> 根元素中。

        (5)Spring IOC 容器中启用 AspectJ 注解支持, 只要Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy>

        (6)Spring IOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理。

4.用 AspectJ 注解声明切面

        要在 Spring 中声明 AspectJ 切面, 只需要在 IOC 容器中将切面声明为 Bean 实例。 当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面相匹配的 Bean 创建代理AspectJ 注解中, 切面只是一个带有 @Aspect 注解的 Java 通知是标注有某种注解的简单的 Java 方法,AspectJ 支持 5 种类型的通知注解:

       @Before: 前置通知, 在方法执行之前执行

       @After: 后置通知, 在方法执行之后执行

       @AfterRunning: 返回通知, 在方法返回结果之后执行

       @AfterThrowing: 异常通知, 在方法抛出异常之后

       @Around: 环绕通知, 围绕着方法执行

5.通知注解说明

       (1)前置通知在方法执行之前执行的通知,前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值。

       (2)后置通知:在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止。一个切面可以包括一个或者多个通知。

       (3)返回通知只要将 returning 属性添加到 @AfterReturning 注解中, 就可以访问连接点的返回值。该属性的值即为用来传入返回值的参数名称。 必须在通知方法的签名中添加一个同名参数在运行时, Spring AOP 会通过这个参数传递返回值。另外,原始的切点表达式需要出现在 pointcut 属性中。

       (4)异常通知:只在连接点抛出异常时才执行异常通知。

            a.throwing 属性添加到 @AfterThrowing 注解中, 也可以访问连接点抛出的异常。Throwable 是所有错误和异常类的  超类所以在异常通知方法可以捕获到任何错误和异常

            b.如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型然后通知就只在抛出这个类型及其子类的异常时才被执行。

       (5)环绕通知:环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点甚至可以控制是否执行连接点

            a.对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint ,它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点

            b.在环绕通知中需要明确调用 ProceedingJoinPoint proceed() 方法来执行被代理的方法如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行。

          注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常。

6.利用方法签名编写 AspectJ 切入点表达式

       最典型的切入点表达式时根据方法的签名来匹配各种方法:

       (1)execution * com.atguigu.spring.ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中声明的所有方法第一个 * 代表任意修饰符及任意返回值第二个 * 代表任意方法. .. 匹配任意数量的参数若目标类与接口与该切面在同一个包中, 可以省略包名

      (2)execution public * ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 接口的所有公有方法

      (3)execution public double ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 返回 double 类型数值的方法。

      (4)execution public double ArithmeticCalculator.*(double, ..): 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数。

       (5)execution public double ArithmeticCalculator.*(double, double): 匹配参数类型为 double, double 类型的方法。

      AspectJ , 切入点表达式可以通过操作符 &&, ||, ! 结合起来。

实例Demo:

public interface ArithmeticCalculator {
	
	public int add(int i,int j);
	public int sub(int i,int j);
	public int mul(int i,int j);
	public int div(int i,int j);
	
}



@Component
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {

	@Override
	public int add(int i, int j) {
		return i+j;
	}

	@Override
	public int sub(int i, int j) {
		return i-j;
	}

	@Override
	public int mul(int i, int j) {
		return i*j;
	}

	@Override
	public int div(int i, int j) {
		return i/j;
	}

}



/**
 * 把这个类声明为一个切面,首先需要把类放到IOC容器中,再声明为一个切面
 * @author psb
 *
 */
@Aspect
@Component
public class LoggingAspect {

	/*
	 * 声明该方法是一个前置通知,在目标方法开始之前执行
	 * @Before("execution(public int com.atguigu.spring.aop.impl.ArithmeticCalculator.add(int,int))")
	 * 
	 */
	@Before("execution(public int com.atguigu.spring.aop.impl.ArithmeticCalculator.*(int,int))") // 通配符,配匹多个方法
	public void beforeMethod(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		List<Object> args = Arrays.asList(joinPoint.getArgs());
		System.out.println("The method " + methodName + " begins with " + args);
	}

	// 后置通知:在目标方法执行后(无论是否发生异常),执行的通知,后置通知中还不能访问目标方法执行的结果
	@After("execution(* com.atguigu.spring.aop.impl.*.div(int,int))")
	public void afterMethod(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method " + methodName + " ends ");
	}

	// 返回通知:在目标方法正常执行后执行的通知,返回通知中是可以访问到方法的返回值的
	@AfterReturning(value = "execution(* com.atguigu.spring.aop.impl.*.div(int,int))", returning = "result")
	public void afterReturning(JoinPoint joinPoint, Object result) { // 参数result和注解@AfterReturning中returning所指定的result保持一致
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method " + methodName + " ends with " + result);
	}

	// 异常通知:在目标方法出现异常时执行的通知,可以返回异常对象,且可以指定在出现特定异常时再执行通知代码
	@AfterThrowing(value = "execution(* com.atguigu.spring.aop.impl.*.div(int,int))", throwing = "e")
	public void afterThrowing(JoinPoint joinPoint, Exception e) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method " + methodName + " occurs exception " + e);
	}

	/**
	 * 环绕通知需要指定ProceedingJointPoint类型的参数,
	 * 环绕通知类似于动态代理的全过程,具备其他4种通知的功能:ProceedingJointPoint类型的参数可以决定是否执行目标方法,
	 * 且环绕通知必须有返回值,返回值即为目标方法的返回值
	 * 
	 */
	@Around("execution(* com.atguigu.spring.aop.impl.*.div(int,int))")
	public Object aroundMethod(ProceedingJoinPoint pjd) {
		Object result = null;
		String methodName = pjd.getSignature().getName();
		try {
			// 前置通知
			System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
			// 执行目标方法
			result = pjd.proceed();
			// 返回通知
			System.out.println("The method ends with " + result);
		} catch (Throwable e) {
			// 异常通知
			System.out.println("The method " + methodName + " occurs exception " + e);
			throw new RuntimeException(e);

		}
		System.out.println("The method " + methodName + " ends ");
		return result;
	}

}



public class Main {

	public static void main(String[] args) {
		
    ApplicationContext ctx=new ClassPathXmlApplicationContext("aop.xml");//指定配置文件在类路径下
		
		ArithmeticCalculator arithmeticCalculator= ctx.getBean(ArithmeticCalculator.class);
		
		int result=arithmeticCalculator.add(3, 6);
		System.out.println("result:"+result);
		
        int result2=arithmeticCalculator.div(12, 0);
		System.out.println("result2:"+result2);

	}

}
<?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 http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

	<context:component-scan base-package="com.atguigu.spring.aop.impl"></context:component-scan>
    <!-- 使AspjectJ注解起作用:自动为配匹的类(注解@Before中声明的类)生成代理对象 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
	
</beans>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值