Spring、XML配置AOP

本文详细介绍了面向切面编程(AOP)的通知机制,包括前置、后置、最终、环绕及例外通知的应用方式,并通过具体代码示例展示了如何在Spring框架中配置这些通知。

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

新建一个AOP类:

public class MyInterceptor2 {
	public void doAccessCheck(){
		System.out.println("前置通知 ");
	}
	public void doAfterReturning(){
		System.out.println("后置通知 ");
	}
	public void doAfter(){
		System.out.println("最终通知");
	}
	public void doAround(ProceedingJoinPoint pjp) throws Throwable{
		System.out.println("环绕通知前");
		pjp.proceed();
		System.out.println("环绕通知后");
	}
	public void doAfterThrowing(Exception e){
		System.out.println("例外通知 例外 e:"+e);
	}
}

在beans.xml中注入,并配置AOP:

<aop:aspectj-autoproxy />
	<bean id="personIService" class="cn.raffaello.service.impl.PersonServiceImpl"/>
	<bean id="myInterceptor2" class="cn.raffaello.aop.MyInterceptor2" />
	<aop:config>
		<!-- 定义切面 -->
		<aop:aspect id="aspect" ref="myInterceptor2">
			<!-- 定义切入点 -->
			<!-- 拦截所有返回值为String的方法:execution(java.lang.String cn.raffaello.service.impl.PersonServiceImpl.*(..)) -->
			<!-- 拦截所有返回值非void的方法:execution(!void cn.raffaello.service.impl.PersonServiceImpl.*(..)) -->
			<!-- 拦截第一个参数是String的方法:execution(* cn.raffaello.service.impl.PersonServiceImpl.*(java.lang.String,..)) -->
			<!-- 拦截包级子包下的所有类的所有的方法:execution(* cn.raffaello.service.*.*(..)) -->
			<!-- 拦截参数为String,并且参数名字为name: execution(* cn.raffaello.service.impl.PersonServiceImpl.*(String)) and args(name) -->
			<aop:pointcut id="pointcut" expression="execution(* cn.raffaello.service.impl.PersonServiceImpl.*(java.lang.String))" />
			<!-- 前置通知 -->
			<aop:before pointcut-ref="pointcut" method="doAccessCheck"/>
			<!-- 后置通知 -->
			<!-- 拦截返回值为String的方法 <aop:after-returning pointcut-ref="pointcut" method="doAfterReturning" returning="retv"/> -->
			<aop:after-returning pointcut-ref="pointcut" method="doAfterReturning" />
			<!-- 最终通知 -->
			<aop:after pointcut-ref="pointcut" method="doAfter" />
			<!-- 环绕通知 -->
			<aop:around pointcut-ref="pointcut" method="doAround" />
			<!-- 例外通知 -->
			<aop:after-throwing pointcut-ref="pointcut" method="doAfterThrowing" throwing="e"/>
		</aop:aspect>
	</aop:config>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值