Spring基于XML文件配置AOP

本文介绍了如何在Spring框架中使用XML配置文件声明切面、切入点及通知等AOP组件,详细展示了各种通知类型的配置方法。

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

一、概述

  1. 除了使用AspectJ声明切面,Spring也支持通过Bean配置文件中声明切面。
  2. 基于注解声明切面,通过AspecJ注解,切面可以与AspectJ兼容,而基于XML文件的配置是Spring专有的,所以通常基于注解的方式要优于基于XML文件方式。

二、基于XML方声明切面

  1. 导入aop命名空间。
  2. 在Bean的配置文件中,配置切面的Bean,必须要有id属性,供<aop:aspect>元素引用。
  3. 在Bean的配置文件中,所有Spring AOP的配置都必须定义在<aop:config>元素内部。
  4. <aop:config>元素内部,定义一个<aop:aspect>元素来声明切面,用其ref属性指定切面的Bean。
  5. 举个例子:
<!-- 配置切面的Bean -->
<bean id="loggingAspectXml" class="com.sqp.spring.aop.xml.LoggingAspectXml"></bean>

<!-- 配置AOP -->
<aop:config>
	<aop:aspect id="loggingAspect" ref="loggingAspectXml"></aop:aspect>
</aop:config>

三、基于XML声明切入点

  1. 必须在<aop:config>元素 或 <aop:aspect>元素下,使用<aop:pointcut>元素声明。
    ① 如果声明在<aop:config>下,对<aop:config>下所有切面有效。
    ② 如果声明在<aop:aspect>下,只对当前切面有效。
  2. 基于XML声明的AOP,不允许在切入点表达式中,用名称引用其他表达式。
  3. 举个例子:
<!-- 配置AOP -->
<aop:config>
	<!-- 配置切点表达式 -->
	<aop:pointcut id="pointcutExpression"
		expression="execution(* com.sqp.spring.aop.dao.MyCalculator.*(int, int))"/>
	<aop:aspect id="loggingAspect" ref="loggingAspectXml"></aop:aspect>
</aop:config>

四、基于XML声明切面的通知

  1. 通知声明在<aop:aspect>元素下,每种通知对应一个XML元素。
    ① 前置通知:<aop:before>
    ② 后置通知:<aop:after>
    ③ 返回通知:<aop:after-returning>
    ④ 异常通知:<aop:after-throwing>
    ⑤ 环绕通知:<aop:around>
  2. method属性指定切面中的通知方法的名称,pointcut-ref 指向<aop:pointcut>元素的id属性。
  3. 举个例子:
<!-- 配置AOP -->
<aop:config>

	<!-- 配置切点表达式 -->
	<aop:pointcut id="pointcutExpression"
	expression="execution(* com.sqp.spring.aop.dao.MyCalculator.*(..))"/>
	
	<!-- 配置loggingAspect切面 -->
	<aop:aspect id="loggingAspect" ref="loggingAspectXml" order="1">
		<!-- 前置通知 -->
		<aop:before method="beforeMethod" pointcut-ref="pointcutExpression"/>
		<!-- 返回通知 -->
		<aop:after-returning method="afterReturningMethod"
			pointcut-ref="pointcutExpression" returning="result"/>
		<!-- 后置通知 -->
		<aop:after method="afterMethod" pointcut-ref="pointcutExpression"/>
		<!-- 异常通知 -->
		<aop:after-throwing method="afterThrowingMethod" 
			pointcut-ref="pointcutExpression" throwing="ex"/>
		<!-- 环绕通知 -->
		<aop:around method="aroundMethod" pointcut-ref="pointcutExpression"/>
	</aop:aspect>
</aop:config>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值