基于xml的方式配置AOP
用基于 XML 的配置聲明切面
除了使用 AspectJ 注解聲明切面, Spring 也支持在 Bean 配置文件中聲明切面. 這種聲明是通過 aop schema 中的 XML 元素完成的.
正常情況下, 基于注解的聲明要優(yōu)先于基于 XML 的聲明. 通過 AspectJ 注解, 切面可以與 AspectJ 兼容, 而基于 XML 的配置則是 Spring 專有的. 由于 AspectJ 得到越來越多的 AOP 框架支持, 所以以注解風(fēng)格編寫的切面將會有更多重用的機(jī)會.
基于 XML ---- 聲明切面
當(dāng)使用 XML 聲明切面時(shí), 需要在 <beans> 根元素中導(dǎo)入 aop Schema
在 Bean 配置文件中, 所有的 Spring AOP 配置都必須定義在 <aop:config> 元素內(nèi)部. 對于每個(gè)切面而言, 都要?jiǎng)?chuàng)建一個(gè) <aop:aspect> 元素來為具體的切面實(shí)現(xiàn)引用后端 Bean 實(shí)例.
切面 Bean 必須有一個(gè)標(biāo)示符, 供 <aop:aspect> 元素引用
聲明切面的實(shí)例代碼
基于 XML ---- 聲明切入點(diǎn)
切入點(diǎn)使用 <aop:pointcut> 元素聲明
切入點(diǎn)必須定義在 <aop:aspect> 元素下, 或者直接定義在 <aop:config> 元素下.
–?定義在 <aop:aspect> 元素下: 只對當(dāng)前切面有效
–?定義在 <aop:config> 元素下: 對所有切面都有效
基于 XML 的 AOP 配置不允許在切入點(diǎn)表達(dá)式中用名稱引用其他切入點(diǎn).
聲明切入點(diǎn)的示例代碼
<?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><!-- 配置目標(biāo)bean --><bean id="arithmeticCalculatorImpl" class="com.learn.spring.aspect_xml.ArithmeticCalculatorImpl"></bean><!-- 配置aop --><aop:config><!-- 配置切入點(diǎn)表達(dá)式 --><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 中, 每種通知類型都對應(yīng)一個(gè)特定的 XML 元素.
通知元素需要使用 <pointcut-ref> 來引用切入點(diǎn), 或用 <pointcut> 直接嵌入切入點(diǎn)表達(dá)式.? method 屬性指定切面類中通知方法的名稱.
?
總結(jié)
以上是生活随笔為你收集整理的基于xml的方式配置AOP的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。