基于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.xsdhttp://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 屬性指定切面類中通知方法的名稱.
?
總結
以上是生活随笔為你收集整理的基于xml的方式配置AOP的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 重用切入点表达式
- 下一篇: Spring事务管理介绍