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">不需要实现任何接口或继承类,只需提供通知方法:
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"/>
使用 <config></config> 定义切面逻辑。常见组合如下:
<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><aop:after-returning
method="afterReturningAdvice"
pointcut-ref="serviceMethod"
returning="result"/><aop:after-throwing
method="exceptionAdvice"
pointcut-ref="serviceMethod"
throwing="ex"/>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"/>
仅配置切面还不够,必须开启 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 仅用于兼容或集中管控切面策略的场景。
以上就是Spring AOP的XML配置方式怎么写的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号