(1)聲明切面
當使用 XML 聲明切面時, 需要在 <beans> 根元素中導入 aop Schema
在 Bean 配置文件中, 所有的 Spring AOP 配置都必須定義在 <aop:config> 元素內部. 對於每個切面而言, 都要創建一個 <aop:aspect> 元素來爲具體的切面實現引用後端 Bean 實例.
切面 Bean 必須有一個標示符, 供 <aop:aspect> 元素引用
(2)聲明切入點
切入點使用 <aop:pointcut> 元素聲明
切入點必須定義在 <aop:aspect> 元素下, 或者直接定義在 <aop:config> 元素下.
定義在 <aop:aspect> 元素下: 只對當前切面有效
定義在 <aop:config> 元素下: 對所有切面都有效
基於 XML 的 AOP 配置不允許在切入點表達式中用名稱引用其他切入點.
(3)聲明通知
通知元素需要使用 <pointcut-ref> 來引用切入點, 或用 <pointcut> 直接嵌入切入點表達式. method 屬性指定切面類中通知方法的名稱.
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!--第一步 配置bean---->
<!-- 配置 bean 將該類納入到IOC容器中 相當於註解的@Component-->
<bean id="arithmeticCalculator"
class="com.spring.aop.xml.ArithmeticCalculatorImpl">
</bean>
<!-- 配置切面的 bean. -->
<bean id="loggingAspect"
class="com.spring.aop.xml.LoggingAspect">
</bean>
<!-- 配置 AOP -->
<aop:config>
<!-- 配置切點表達式 -->
<aop:pointcut expression="execution(* com.spring.aop.xml.ArithmeticCalculator.*(int, int))"
id="pointcut"/>
<!-- 配置切面及通知 和註解的@Aspect @Before等作用一致 -->
<aop:aspect ref="loggingAspect" order="1">
<aop:before method="beforeMethod" pointcut-ref="pointcut"/>
<aop:after method="afterMethod" pointcut-ref="pointcut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<!--
<aop:around method="aroundMethod" pointcut-ref="pointcut"/>
-->
</aop:aspect>
</aop:config>
</beans>