您现在的位置是:首页 > 个人日记个人日记

spring-08-AOP-XML配置详细介绍

2019-02-03 18:47:09【个人日记】619人已围观

简介使用XML来配置AOP环境

XML配置详细介绍

spring-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. 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">
  5. <!--目标-->
  6. <bean id="UserService" class="com.spring.service.UserService"></bean>
  7. <!--增强类-->
  8. <bean id="TransationAdvice" class="com.spring.aspect.TransactionAdvice"></bean>
  9. <!--切面,生成动态代理,将增强注入-->
  10. <aop:config>
  11. <!--引入增强-->
  12. <aop:aspect ref="TransationAdvice">
  13. <!--切入点-->
  14. <!--execution表达式仔细看-->
  15. <aop:pointcut id="transationPointCut"
  16. expression="execution(* com.spring.service.UserService.*(*))"></aop:pointcut>
  17. <!--前置通知-->
  18. <aop:before method="brfore" pointcut-ref="transationPointCut"></aop:before>
  19. <!--后置通知 如果发生错误将不再执行-->
  20. <aop:after-returning method="afterReturning" pointcut-ref="transationPointCut"></aop:after-returning>
  21. <!--最终通知,始终被执行-->
  22. <aop:after method="after" pointcut-ref="transationPointCut"></aop:after>
  23. <!--出错通知,只有出错才会执行-->
  24. <aop:after-throwing method="afterThrowing" pointcut-ref="transationPointCut"
  25. throwing="e"></aop:after-throwing>
  26. </aop:aspect>
  27. </aop:config>
  28. </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  

评论区

    2024-04-19 05:10:19

    站长

    没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信


文章评论



给自个选个头像吧!






站点信息

  • 建站时间:   2019-01-31
  • 网站程序:   Tomcat+nginx
  • 文章统计:   44篇文章
  • 标签管理:   标签云
  • 微信公众号:  扫描二维码,联系我