Spring AOP XML 配置适用于旧版项目,需声明 aop 命名空间、定义切面 Bean、用配置 pointcut 与各类 advice,并启用 proxy-target-class=true 以支持 CGLIB 代理。

Spring AOP 的 XML 配置方式在较老的 Spring 项目(如 Spring 3.x 或早期 4.x)中常用,虽然现在主流用注解(@Aspect、@Before 等),但理解 XML 配置有助于阅读遗留代码或满足特定部署约束。
基础依赖与命名空间声明
确保项目引入了 spring-aop 和 aspectjweaver 依赖,并在 Spring 配置文件 (如 applicationContext.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/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
定义切面类(普通 Java 类)
不需要实现任何接口或继承类,只需提供通知方法:
public class LoggingAspect {public void beforeAdvice() {System.out.println("【前置通知】方法执行前记录日志 "); } public void afterReturningAdvice(Object result) {System.out.println("【返回通知】方法返回值:" + result); } }
然后在 XML 中将其声明为一个 bean:
<bean id="loggingAspect" class="com.example.LoggingAspect"/>
配置切点(pointcut)和通知(advice)
使用 <config></config> 定义切面逻辑。常见组合如下:
- 前置通知(before):
<aop:config> <aop:aspect ref="loggingAspect"> <aop:pointcut id="serviceMethod" expression="execution(* com.example.service..*.*(..))"/> <aop:before method="beforeAdvice" pointcut-ref="serviceMethod"/> </aop:aspect> </aop:config> - 后置返回通知(after-returning),支持获取返回值:
<aop:after-returning method="afterReturningAdvice" pointcut-ref="serviceMethod" returning="result"/> - 异常通知(after-throwing):
<aop:after-throwing method="exceptionAdvice" pointcut-ref="serviceMethod" throwing="ex"/> - 环绕通知(around),最灵活(需方法签名含
ProceedingJoinPoint):
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {System.out.println("【环绕 - 前】"); Object result = joinPoint.proceed(); // 执行原方法 System.out.println("【环绕 - 后】"); return result; }<aop:around method="aroundAdvice" pointcut-ref="serviceMethod"/>
启用 AspectJ 自动代理(关键!)
仅配置切面还不够,必须开启 AOP 代理机制。Spring 默认使用 JDK 动态代理 (针对接口),若目标类无接口,需配合 CGLIB(添加 proxy-target-class="true"):
<aop:config proxy-target-class="true"> <!-- 切面内容 --> </aop:config>
或者全局启用 CGLIB 代理(等价效果):
<aop:aspectj-autoproxy proxy-target-class="true"/>
注意:<aspectj-autoproxy></aspectj-autoproxy> 是另一种写法,适用于已用 @Aspect 注解但想通过 XML 启用的场景;纯 XML 配置推荐用 <config></config>。
基本上就这些。XML 方式清晰直观,但冗长;实际开发中建议优先用注解,XML 仅用于兼容或集中管控切面策略的场景。