基于xml的方式配置AOP

用基于 XML 的配置声明切面

除了使用 AspectJ 注解声明切面, Spring 也支持在 Bean 配置文件中声明切面. 这种声明是通过 aop schema 中的 XML 元素完成的.

正常情况下, 基于注解的声明要优先于基于 XML 的声明. 通过 AspectJ 注解, 切面可以与 AspectJ 兼容, 而基于 XML 的配置则是 Spring 专有的. 由于 AspectJ 得到越来越多的 AOP 框架支持, 所以以注解风格编写的切面将会有更多重用的机会.

基于 XML ---- 声明切面

当使用 XML 声明切面时, 需要在 <beans> 根元素中导入 aop Schema

Bean 配置文件中, 所有的 Spring AOP 配置都必须定义在 <aop:config> 元素内部. 对于每个切面而言, 都要创建一个 <aop:aspect> 元素来为具体的切面实现引用后端 Bean 实例.

切面 Bean 必须有一个标示符, <aop:aspect> 元素引用

声明切面的实例代码

基于 XML ---- 声明切入点

切入点使用 <aop:pointcut> 元素声明

切入点必须定义在 <aop:aspect> 元素下, 或者直接定义在 <aop:config> 元素下.

– 定义在 <aop:aspect> 元素下: 只对当前切面有效

– 定义在 <aop:config> 元素下: 对所有切面都有效

基于 XML AOP 配置不允许在切入点表达式中用名称引用其他切入点.

声明切入点的示例代码

<?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/aop 
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- 配置切面 -->
	<bean id="loggingAspect" class="com.learn.spring.aspect_xml.LoggingAspect"></bean>
	<bean id="validatorAspect" class="com.learn.spring.aspect_xml.ValidatorAspect"></bean>
	
	<!-- 配置目标bean -->
	<bean id="arithmeticCalculatorImpl" class="com.learn.spring.aspect_xml.ArithmeticCalculatorImpl"></bean>
	
	<!-- 配置aop -->
	<aop:config>
		<!-- 配置切入点表达式 -->
		<aop:pointcut expression="execution(* com.learn.spring.aspect_xml.*.*(..))"
					 id="myPointCut"/>
		<!-- 配置切面及通知 -->
		<aop:aspect ref="loggingAspect"  order="1">
			<aop:before method="beforeMethod" pointcut-ref="myPointCut"/>
			<aop:after method="afterMethod" pointcut-ref="myPointCut"/>
			<aop:after-returning method="afterReturningMethod" pointcut-ref="myPointCut" returning="result"/>
			<aop:after-throwing method="afterThrowingMethod" pointcut-ref="myPointCut" throwing="ex"/>
		</aop:aspect>
		
		<!-- <aop:aspect order="2"></aop:aspect> -->
		
	</aop:config>
	
</beans>

基于 XML ---- 声明通知

aop Schema , 每种通知类型都对应一个特定的 XML 元素.

通知元素需要使用 <pointcut-ref> 来引用切入点, 或用 <pointcut> 直接嵌入切入点表达式.  method 属性指定切面类中通知方法的名称.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值