(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>