AspectJ环绕通知

本文介绍如何使用AspectJ在一个类中统一管理所有类型的通知,包括前置、后置、返回、异常和环绕通知,并通过示例代码展示其配置及运行效果。在没有错误的情况下,各通知按顺序执行;当出现异常时,<aop:after/>标签依然执行。

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

AspectJ的好处是可以将所有的通知写到一个类中,二schema-based需要不同的类实现不同的接口
例如

public class MyAdvice {
	public void beforeMethod() {
		System.out.println("before");
	}
	public void afterMethod() {
		System.out.println("after");
	}
	public void after_returning_Method() {
		System.out.println("after_returning");
	}
	public void throwMethod() {
		System.out.println("throw");
	}
	public Object aroundMethod(ProceedingJoinPoint pj) throws Throwable{
		System.out.println("around before");
		Object result = pj.proceed();
		System.out.println("around after");
		return result;
	}
}

配置xml

<bean id="demo" class="com.lee.service.DemoService"/>        
<bean id="myadvice" class="com.lee.advice.MyAdvice"/>
<aop:config> 
	<aop:pointcut expression="execution(* com.lee.service.*.*(..))" id="mypoint"/>       	    
	<aop:aspect ref="myadvice">
		<aop:before method="beforeMethod" pointcut-ref="mypoint"/>
		<aop:after-returning method="after_returning_Method" pointcut-ref="mypoint"/>
		<aop:after method="afterMethod" pointcut-ref="mypoint"/>
		<aop:around method="aroundMethod" pointcut-ref="mypoint"/>	   
		<aop:after-throwing method="throwMethod" pointcut-ref="mypoint"/>    	
	</aop:aspect>
</aop:config>

切点类

public class DemoService {
	public void demoMethod() {
		//int i = 5/0;
		System.out.println("DemoMethod execute");
	}
}

当切点没有错误时,结果如下

before
around before
DemoMethod execute
around after
after
after_returning

当有错误时

before
around before
throw
after
Exception in thread "main" java.lang.ArithmeticException: / by zero

可见当有没有错误,<aop:after/>标签始终执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值