通过 XML 配置文件声明
在前两篇博文和示例中,我们已经展示了如何通过注解配置去声明切面,下面我们看看如何在 XML 文件中声明切面。下面先列出 XML 中声明 AOP 的常用元素:
AOP配置元素 | 用途 |
---|---|
aop:advisor | 定义AOP通知器 |
aop:after | 定义AOP后置通知(不管被通知的方法是否执行成功) |
aop:after-returning | 定义AOP返回通知 |
aop:after-throwing | 定义AOP异常通知 |
aop:around | 定义AOP环绕通知 |
aop:aspect | 定义一个切面 |
aop:aspectj-autoproxy | 启用@AspectJ注解驱动的切面 |
aop:before | 定义一个AOP前置通知 |
aop:config | 顶层的AOP配置元素。大多数的aop:*元素必须包含在aop:config元素内 |
aop:declare-parents | 以透明的方式为被通知的对象引入额外的接口 |
aop:pointcut | 定义一个切点 |
XML 配置文件中切点指示器
在XML配置文件中,切点指示器表达式与通过注解配置的写法基本一致,区别前面有提到,即XML文件中需要使用 “and”、“or”、“not”来表示 “且”、“或”、“非”的关系。
XML 文件配置 AOP
新建OrderXmlAop.java:
package com.example.demo.aop;
public class OrderXmlAop {
/**
* @description 在连接点执行之前执行的通知
*/
public void doBefore(){
System.out.println("阿里阿塞哟!");
}
/**
* @description 在连接点执行之后执行的通知(返回通知和异常通知的异常)
*/
public void doAfter(){
System.out.println("after!");
}
/**
* @description 在连接点执行之后执行的通知(返回通知)
*/
public void doAfterReturning(){
System.out.println("返回通知:AfterReturning");
}
/**
* @description 在连接点执行之后执行的通知(异常通知)
*/
public void doAfterThrowing(){
System.out.println("异常通知:AfterThrowing");
}
}
在 Resource 目录下新建一个配置文件 aoporder.xml :
<?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.xsd">
<bean id="wmzService" class="com.example.demo.service.impl.WMZServiceImpl"></bean>
<bean id="zsService" class="com.example.demo.service.impl.ZSServiceImpl"></bean>
<!-- 切面类 -->
<bean id="OrderXmlAop" class="com.example.demo.aop.OrderXmlAop"></bean>
<!-- Aop配置 -->
<aop:config proxy-target-class="true"