[Spring]Spring AOP学习笔记(2)---5种切入方式、AOP优先级及切面表达式的重用

本文介绍了Spring AOP的五种切入方式(Before, After, AfterReturning, AfterThrowing, Around)及其应用场景,讨论了After与AfterReturning的区别,并详细说明了AOP切面的优先级设定,利用@Order注解控制执行顺序。此外,还探讨了切面表达式的重用方法,通过@Pointcut实现。最后,提到了AOP的XML配置方式,并强调了@Around方法返回类型与被拦截方法的一致性问题。文章结合作者在华为实习期间使用AOP记录日志的经验,提醒读者注意AOP配置的细节。" 134623899,643027,RTP分析:RtpPacket与RtpPacketToSend的扩展操作详解,"['webrtc', '网络通信', '协议分析', '编程实践', '内存管理']

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

Spring AOP学习笔记(2)---5种切入方式、AOP优先级及切面表达式的重用

一、5种切入方式

学习了下Spring的AOP的五种切入方式,分别是:

(1)Before ---在所拦截方法执行前执行;

(2)After ---在所拦截方法执行后执行;

(3)AfterRuturning  ---在所拦截方法返回值后,执行;

(4)AfterThrowing ---当所拦截方法抛出异常时,执行;

(5)Around ---最为复杂的切入方式,刚方式可以包括上述4个方式。


现在假设切入点为A_Method(假设该方法的执行输出为“A”)。

方式(1)的切入方式的结果为:

             before

             A


方式(2)的切入方式的结果为:

             A

     after


方式(3)的切入方式的结果为:

             A

    afterreturning

方式(4)的切入方式的结果为:

         (有异常,则抛出,执行)


方式(5)的切入方式的结果为:

         可以是上述四种的任意组合。


对于方式(2)(3),是一样的么?其实不然。

区别:拦截方法不管是否有异常,都会执行的是方式(2),即After的切入方式。类似于try-catch-finally,在finally里面的语句。而方式(3)只有当拦截方法成功执行才会执行。

可通过有异常的方法来测试区别(笔者采用的是除0异常)。


二、AOP优先级

如果同时有2个AOP切面,那么如何设定优先级呢?Spring提供了“@order()”的注解方式,@order(1)则表示优先级最高,order(n),n越小,优先级越高。如下例。


图1


图2


图2的加载是优于图1的。 


三、切面表达式的重用

我们发现,添加注解时,我们有相同的内容,这样的东西是否可以重用呢?答案是肯定的。

通过@Pointcut()即可完成切面表达式的重用。如下例。

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(3)
@Aspect
@Component
public class testAspect {
	@Pointcut("execution(* com.spring.aop.test1.*.*(int,int))")
	public void asp(){
		
	}
	
	@Before("asp()")
	public void beforeMethod(JoinPoint joinpoint){
		Object name = joinpoint.getSignature().getName();
		Object[] list = joinpoint.getArgs();
		System.out.println("before.."+name+":"+Arrays.asList(list));
	}
	
	@After("asp()")
	public void afterMethod(){
		System.out.println("after..");
	}
	
	@AfterReturning("asp()")
	public void afterReturningMethod(){
		System.out.println("afterreturn..");
	}
	}


四、AOP的XML配置方式

上一篇记录了AOP的5种切入方式,但是所有的bean都是基于注解的方式来添加进容器的,这一节采用配置文件方式进行配置。贴上代码。如下。

package com.spring.aop.test3;

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

package com.spring.aop.test3;


public class jisuanimpl implements jisuan {

	@Override
	public int add(int i, int j) {
		// TODO Auto-generated method stub
//		System.out.println("add is begin..");//mul,sub,div都是
		int result = i+j;
		System.out.println(result);
//		System.out.println("add is over..");
		return result;
	}

	@Override
	public int mul(int i, int j) {
		// TODO Auto-generated method stub
		int result = i*j;
		System.out.println(result);
		return result;
	}

	@Override
	public int sub(int i, int j) {
		// TODO Auto-generated method stub
		int result = i-j;
		System.out.println(result);
		return result;
	}

	@Override
	public int div(int i, int j) {
		// TODO Auto-generated method stub
		int result = i/j;
		System.out.println(result);
		return result;
	}

}

package com.spring.aop.test3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-aop-2.xml");
		jisuan js = (jisuan) ctx.getBean("js"); 
		js.add(4, 2);
	}
}

package com.spring.aop.test3;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class testAspect {
	public void asp() {

	}

	public void beforeMethod(JoinPoint joinpoint) {
		Object name = joinpoint.getSignature().getName();
		Object[] list = joinpoint.getArgs();
		System.out.println("before.." + name + ":" + Arrays.asList(list));
	}

	public void afterMethod() {
		System.out.println("after..");
	}

	public void afterReturningMethod() {
		System.out.println("afterreturn..");
	}

	public int aroundMethod(ProceedingJoinPoint pjp) {
		int result = 0;
		try {
			System.out.println("before method..");
			result=(int) pjp.proceed();
			System.out.println("afterreturning method..");
		} catch (Exception e) {
			System.out.println("throwable exception..");
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("after method..");
		return result;
	}

}


<?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: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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
	<bean id="js" class="com.spring.aop.test3.jisuanimpl"></bean>
	<bean id="testAspect" class="com.spring.aop.test3.testAspect"></bean>
	<!-- 配置AOP -->
	<aop:config>
		<!-- 配置切面表达式 -->
		<aop:pointcut expression="execution(* com.spring.aop.test3.*.*(int,int))"
			id="point" />
		<aop:aspect ref="testAspect" order="1">
		<!-- 	<aop:before method="beforeMethod" pointcut-ref="point" />
			<aop:after method="afterMethod" pointcut-ref="point"/> -->
			
		<!-- 环绕通知 -->
		<aop:around method="aroundMethod" pointcut-ref="point"/>
		</aop:aspect>
	</aop:config>
</beans>


下面的为运行结果。



在编写@around的method遇到错误: Exception in thread "main"org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: ........

原因是,@around()方法指定的方法的返回值类型必须是和拦截方法的返回值数据类型一致。本例的add()、mul()等方法的返回类型为int,那么@around()指定的方法的返回类型必须是int,不然会报上面的错。

---------------------分割线----------------------------


2016年6月21日,在华为实习期间,使用Spring AOP解决了记录日志的功能。

特此记录一些心得:

(1)这篇我所写的博文,时隔一年再来看,内容较为粗糙

(2)AOP的配置,可以仅仅通过XML进行配置,也可以通过注解的方式进行配置。

(3)配置如@Around等切入方式的方法,其返回类型应与切入点保持一致,这一点在其他很多博文中都没有看到有所体现。这里需要注意下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值