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 命名空间:
定义切面类(普通 Java 类)
不需要实现任何接口或继承类,只需提供通知方法:
public class LoggingAspect {
public void beforeAdvice() {
System.out.println("【前置通
知】方法执行前记录日志");
}
public void afterReturningAdvice(Object result) {
System.out.println("【返回通知】方法返回值:" + result);
}
}然后在 XML 中将其声明为一个 bean:
配置切点(pointcut)和通知(advice)
使用 定义切面逻辑。常见组合如下:
-
前置通知(before):
-
后置返回通知(after-returning),支持获取返回值:
-
异常通知(after-throwing):
-
环绕通知(around),最灵活(需方法签名含
ProceedingJoinPoint):public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("【环绕-前】"); Object result = joinPoint.proceed(); // 执行原方法 System.out.println("【环绕-后】"); return result; }
启用 AspectJ 自动代理(关键!)
仅配置切面还不够,必须开启 AOP 代理机制。Spring 默认使用 JDK 动态代理(针对接口),若目标类无接口,需配合 CGLIB(添加 proxy-target-class="true"):
或者全局启用 CGLIB 代理(等价效果):
注意: 是另一种写法,适用于已用 @Aspect 注解但想通过 XML 启用的场景;纯 XML 配置推荐用 。
基本上就这些。XML 方式清晰直观,但冗长;实际开发中建议优先用注解,XML 仅用于兼容或集中管控切面策略的场景。

知】方法执行前记录日志");
}
public void afterReturningAdvice(Object result) {
System.out.println("【返回通知】方法返回值:" + result);
}
}






