您现在的位置是:首页 > 个人日记个人日记
spring-08-AOP-XML配置详细介绍
2019-02-03 18:47:09【个人日记】758人已围观
简介使用XML来配置AOP环境
XML配置详细介绍
spring-config.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="UserService" class="com.spring.service.UserService"></bean><!--增强类--><bean id="TransationAdvice" class="com.spring.aspect.TransactionAdvice"></bean><!--切面,生成动态代理,将增强注入--><aop:config><!--引入增强--><aop:aspect ref="TransationAdvice"><!--切入点--><!--execution表达式仔细看--><aop:pointcut id="transationPointCut"expression="execution(* com.spring.service.UserService.*(*))"></aop:pointcut><!--前置通知--><aop:before method="brfore" pointcut-ref="transationPointCut"></aop:before><!--后置通知 如果发生错误将不再执行--><aop:after-returning method="afterReturning" pointcut-ref="transationPointCut"></aop:after-returning><!--最终通知,始终被执行--><aop:after method="after" pointcut-ref="transationPointCut"></aop:after><!--出错通知,只有出错才会执行--><aop:after-throwing method="afterThrowing" pointcut-ref="transationPointCut"throwing="e"></aop:after-throwing></aop:aspect></aop:config></beans>
重点
1) 设置顺序要注意
2) execution表达式要理解
3) 当出错时,后置通知将不在执行
4) 最终通知无论怎样都会执行
5) afterReturning可以拿到返回值
使用around实现AOP
在增强代码中加入around
```java
package com.spring.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
public class TransactionAdvice {
/**
* 使用环绕通知
*
* @param proceedingJoinPoint
* @return
*/
public Object around(ProceedingJoinPoint proceedingJoinPoint) {
Object result = null;
try {
System.out.println("开启事务");
result = proceedingJoinPoint.proceed();
System.out.println("提交事务");
} catch (Throwable throwable) {
result = 500;
System.out.println("回滚事务");
throwable.printStackTrace();
} finally {
System.out.println("释放资源");
}
return result;
}
}
```
配置spring-config.xml文件
```xml
```
Tags: JavaWeb
上一篇: 网页抓取工具
下一篇: mybatis-07-单表一对多查询
相关文章
随机图文
评论区
2025-11-09 06:22:55
站长
没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信
