【Spring-AOP-学习笔记-7】@Around增强处理简单示例

阅读目录


Around 增强处理-简单介绍

  • 既可以在目标方法之前织入增强动作,也可以在执行目标方法之后织入增强动作;
  • 它可以决定目标方法在什么时候执行,如何执行,甚至可以完全阻止目标目标方法的执行;
  • 它可以改变执行目标方法的参数值,也可以改变执行目标方法之后的返回值;
  • 当需要改变目标方法的返回值时,只能使用Around方法;
虽然Around功能强大,但通常需要在线程安全的环境下使用。因此,如果使用普通的Before、AfterReturing增强方法就可以解决的事情,就没有必要使用Around增强处理了。

一、项目结构

二、定义切面类、连接点注解类


PointCut连接点注解类
说明:
这是一个注解类型:@interface
类中设置了一个methodName属性;

定义切面类
说明:
  • @Around定义了此方法为 Around增强处理方法;
  • @annotation(around):参数around应该与增强处理方法中的参数名保持一致,该声明指定了pointcut连接点,也可以使用其他方式,如:
 pointcut="execution(* org.crazyit.app.service.impl.*.*(..))";
  • point.proceed()调用了目标方法,并获取其返回值;

三、为待增强的方法--添加注解声明

在上面定义@Around增强时,通过@annotation() 方式指定了pointcut,其中方法参数为连接点注解类aroundAuthority
如果需要对某一方法进行增强,只需要在相应的方法上添加上此注解即可,如下:

四、AspectJ配置文件


  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:tx="http://www.springframework.org/schema/tx"
  4. xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  8. http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  11. <!-- 启动@AspectJ支持 -->
  12. <aop:aspectj-autoproxy />
  13. <context:component-scan base-package="com.sssppp.Spring.aop">
  14. </context:component-scan>
  15. </beans>

五、测试类



六、测试结果

可能的输出结果:






七、其他类型增强处理方式

@AfterThrowing增强处理简单示例http://www.cnblogs.com/ssslinppp/p/4633595.html 
《@AfterReturning增强处理简单示例》http://www.cnblogs.com/ssslinppp/p/4633496.html 
《@After后向增强处理简单示例》http://www.cnblogs.com/ssslinppp/p/4633427.html 
《@Before前向增强处理简单示例》 http://www.cnblogs.com/ssslinppp/default.html?page=7 







原文地址:https://www.cnblogs.com/ssslinppp/p/5845659.html