Spring-AOP:基于配置文件方式的AOP

来源:互联网 发布:js select 不可编辑 编辑:程序博客网 时间:2024/05/17 07:26
除了使用 AspectJ 注解声明切面, Spring 也支持在 Bean 配置文件中声明切面. 这种声明是通过 aop schema 中的 XML 元素完成的.

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

当使用 XML 声明切面时, 需要在 <beans> 根元素中导入 aop Schema
在 Bean 配置文件中, 所有的 Spring AOP 配置都必须定义在 <aop:config> 元素内部. 对于每个切面而言, 都要创建一个<aop:aspect> 元素来为具体的切面实现引用后端 Bean 实例.
切面 Bean 必须有一个标示符, 供 <aop:aspect> 元素引用

声明切面

在声明切面之前,需要先为切面类声明一个普通bean。然后在<aop:config>中使用<aop:aspect> 声明为一个切面:

<bean id="arithmeticCalculator" class="com.atguigu.spring.aop.xml.ArithmeticCalculatorImpl"></bean><bean id="loggingAspect"class="com.atguigu.spring.aop.xml.LoggingAspect"></bean><bean id="validatingAspect"class="com.atguigu.spring.aop.xml.ValidatingAspect"></bean><!-- 配置AOP --><aop:config><!-- 配置切面 --><aop:aspect ref="loggingAspect" order="2"></aop:aspect><aop:aspect ref="validatingAspect" order="1"></aop:aspect></aop:config>

在声明切面的时候也可以配置一个id,此外还可以通过order属性指定切面优先级。

声明切入点

切入点使用<aop:pointcut> 元素声明
切入点必须定义在 <aop:aspect> 元素下, 或者直接定义在 <aop:config> 元素下.
--定义在 <aop:aspect> 元素下: 只对当前切面有效
--定义在 <aop:config> 元素下: 对所有切面都有效
基于 XML 的 AOP 配置不允许在切入点表达式中用名称引用其他切入点.

<!-- 配置切点表达式 --><aop:pointcut expression="execution(* com.atguigu.spring.aop.xml.ArithmeticCalculator.*(..))" id="arithPointcut"/>

声明通知

这里的通知就是指前置、后置、返回、异常、环绕等类型的通知。

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

前置通知:<aop:before />

后置通知:<aop:after />

返回通知:<aop:after-returning />

异常通知:<aop:after-throwing />

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

示例如下:

<!-- 配置AOP --><aop:config><!-- 配置切点表达式 --><aop:pointcut expression="execution(* com.atguigu.spring.aop.xml.ArithmeticCalculator.*(..))" id="arithPointcut"/><!-- 配置切面及通知 --><aop:aspect ref="loggingAspect" order="2"><aop:before method="beforeMethod" pointcut-ref="arithPointcut"/><aop:after method="afterMethod" pointcut-ref="arithPointcut"/><!-- 注意这里多了一个returning属性配置,而且其值必须与方法的参数名一致 --><aop:after-returning method="returningMethod" pointcut-ref="arithPointcut" returning="result"/><!-- 这里必须配置throwing,其值也必须与方法的参数名一致 --><aop:after-throwing method="afterThrowing" pointcut-ref="arithPointcut" throwing="e"/><!-- 配置环绕通知 --><!-- <aop:around method="aroundMethod" pointcut-ref="arithPointcut"/>  --></aop:aspect><aop:aspect ref="validatingAspect" order="1"><aop:before method="validateArgs" pointcut-ref="arithPointcut"/></aop:aspect></aop:config>


0 0