零、准备知识

1)AOP相关概念:Aspect、Advice、Join point、Pointcut、Weaving、Target等。
2)相关注解:@Aspect、@Pointcut、@Before、@Around、@After、@AfterReturning、@AfterThrowing
 

一、实践目标

1)@Aspect的功能
2)@Pointcut的切面表达式
3)@Before、@Around、@After、@AfterReturning / @AfterThrowing的时序关系
4)AOP概念的重新梳理和使用

二、核心代码

MainController.java包含两个测试函数,分别是doSomething() 和 test()。
 // MainController.java
@RestController
public class MainController {
RequestMapping(value="/doSomething", method = RequestMethod.POST)
@CrossOrigin("*")
public void doSomething() {
System.out.println("This is doSomething");
test();
} @RequestMapping(value="/justTest", method = RequestMethod.POST)
@CrossOrigin("*")
public void test() { System.out.println("This is test");}
}

ExampleAop.java为AOP相关代码,定义了pointcut和多个Advice函数。

 // ExampleAop.java
@Component
@Aspect
@Order(1)
public class ExampleAop { private static final Logger LOGGER = LoggerFactory.getLogger(ExampleAop.class); // 匹配com.example.demo包及其子包下的所有类的所有方法
@Pointcut("execution(* com.example.demo..*.*(..))")
public void executeService() {
} @Before("executeService()")
public void doBeforeAdvice(JoinPoint joinPoint) throws Exception {
LOGGER.info("Before [{}]", joinPoint.getSignature().getName());
} @Around("executeService()")
public void doAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
LOGGER.info("Around1 [{}]", joinPoint.getSignature().getName());
joinPoint.proceed();
LOGGER.info("Around2 [{}]", joinPoint.getSignature().getName());
} @After("executeService()")
public void doAfterAdvice(JoinPoint joinPoint) throws Exception {
LOGGER.info("After [{}]", joinPoint.getSignature().getName());
} @AfterReturning("executeService()")
public void doAfterReturningAdvice(JoinPoint joinPoint) throws Exception {
LOGGER.info("AfterReturning [{}]", joinPoint.getSignature().getName());
}
}

编译并运行jar包,调用接口/doSomething。

 # 调用接口
curl localhost:8080/doSomething

到服务器观察日志。

 <!-- 后台日志 -->
com.example.demo.aop.ExampleAop : Around1 [doSomething]
com.example.demo.aop.ExampleAop : Before [doSomething]
This is doSomething
This is test
com.example.demo.aop.ExampleAop : Around2 [doSomething]
com.example.demo.aop.ExampleAop : After [doSomething]
com.example.demo.aop.ExampleAop : AfterReturning [doSomething]

三、分析与结论

1)@Aspect的功能
  在连接点的前后添加处理。在本例中,doSomething() 是连接点,而test() 不是。
  是否只有最外层的joinpoint才会被Advice插入?在后面进行简单的探讨和猜测。
 
 
2)@Pointcut的切面表达式
  ref: https://www.jianshu.com/p/fbbdebf200c9  完整表达式
  @Pointcut("execution(...)") 是Pointcut表达式,executeService() 是point签名。表达式中可以包含签名的逻辑运算。
 
  常用表达式:
 execution(public * com.example.demo.ExampleClass.*(..))  // ExampleClass的所有公有方法
execution(* com.example.demo..*.*(..)) // com.example.demo包及其子包下的所有方法
logSender() || logMessage() // 两个签名的表达式的并集
3)@Before、@Around、@After、@AfterReturning / @AfterThrowing的时序关系
  @Around1 -> @Before -> 方法 -> @Around2 -> @After -> @AfterReturning / @AfterThrowing(时序问题后面有额外讨论。)
  另外可以发现,@Around是可以影响程序本身执行的,如果不调用 joinPoint.proceed(); 就不会执行方法。其他几个都无法影响程序执行。
 
 
4)AOP概念的重新梳理和使用
  Aspect(切面):使用了@Aspect注解,如ExampleAop类。
  Advice(增强):在指定位置进行的增强操作,如方法运行时间统计、用户登录、日志记录等。由@Before、@After等注解标注,如doBeforeAdvice() 方法。
  Weaving(织入):AOP就是一种把Advice织入(即嵌入、插入)到Aspect中指定位置执行的机制。
  Join point(连接点):Advice执行的位置,也是Advice的参数,是一个具体的方法。如日志中看到的doSomething() 函数。
  Pointcut(切点):以表达式的形式表示一组join point,用于由@Pointcut注解定义Advice的作用位置。如@Pointcut("execution(* com.example.demo..*.*(..))") 代表com.example.demo包及其子包下的所有类的所有方法。
  Target(对象):被增强的对象,即包含主业务逻辑的类的对象,如ExampleAop类的实例。

四、疑问与讨论

1. 本文说执行顺序为@Around1 -> @Before -> 方法 -> @Around2 -> @After,但有的文章中说是@Before -> @Around1 -> 方法 -> @Around2 -> @After,也有说@Around1 -> @Before -> 方法 -> @After -> @Around2,哪个对?
 
  反正代码跑起来是这个顺序,那就是这个顺序喽。每个Advice都加上sleep拉开时间也没有变化。不知道是否受版本或代码自身影响。
  总之可以得到一个结论:@Before / @After 最好不要和@Around混用,执行顺序不好确定。
  时序至少总是满足:@Around1 / @Before -> 方法 -> @Around2 / @After -> @AfterReturning / @AfterThrowing
  另外找到一篇支持本文执行顺序的文章:https://blog.csdn.net/qq_32331073/article/details/80596084
 
 
2. 为何doSomething() 和 test() 都是@Pointcut中选中的作用节点,但只有doSomething() 插入了Advice,而test() 没有呢?
 
        一个猜测:从字面意思理解,@Pointcut对所有代码以表达式为规则剪一刀,一侧是所有的joinpoint,另一侧是普通代码。在joinpoint与另一侧代码间插入一层Advice的代理,另一侧的代码如果要调用joinpoint,则必须经Advice进行增强操作。而不同的joinpoint在同一侧,因此未插入Advice。
        有时间再读源码了解其中的机制。

(一个猜测)

五、Future Work

1. AOP中还有Advisor等概念,待学习。
2. 切面表达式(@Pointcut里的表达式)规则丰富,待学习。
3. Advice的插入时机,待读源码学习。

Spring入门之AOP实践:@Aspect + @Pointcut + @Before / @Around / @After的更多相关文章

  1. Spring入门4.AOP配置深入

    Spring入门4.AOP配置深入 代码下载 链接: http://pan.baidu.com/s/11mYEO 密码: x7wa 前言: 之前学习AOP中的一些概念,包括连接点.切入点(pointc ...

  2. Spring入门3.AOP编程

    Spring入门3.AOP编程 代码下载: 链接: http://pan.baidu.com/s/11mYEO 密码: x7wa 前言: 前面学习的知识是Spring在Java项目中的IoC或DJ,这 ...

  3. Spring基础系列--AOP实践

    原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9615720.html 本文目的是简单讲解下Spring AOP的使用. 推荐使用IDEA ...

  4. Spring入门之AOP篇

    听了几节IT黑马营的SPRING课程,照着例程写了一个SPRING 中AOP的例子:  一.准备工作 下载复制或配置JAR包.图方便,我将下载的SPRING包都加上去了.另外还需要aspectj的两个 ...

  5. Spring入门篇——AOP基本概念

    1.什么是AOP及实现方式 什么是AOP AOP:Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术 主要 ...

  6. spring 注解 之 AOP基于@Aspect的AOP配置

    Spring AOP面向切面编程,可以用来配置事务.做日志.权限验证.在用户请求时做一些处理等等.用@Aspect做一个切面,就可以直接实现. 1.首先定义一个切面类,加上@Component  @A ...

  7. Spring入门介绍-AOP(三)

    AOP的概念 AOP是面向切面编程的缩写,它是一种编程的新思想.对我们经常提起的oop(面对对象编程)有一定的联系. AOP和OOP的关系 AOP可以说是oop的某一方便的补充,oop侧重于对静态的属 ...

  8. Spring课程 Spring入门篇 5-3 配置切入点 pointcut

    1 解析 1.1 xml常见的配置切入点写法 2 代码演练 2.1 xml配置切入点   1 解析 1.1 xml常见的配置切入点写法 2 代码演练 2.1 xml配置切入点 xml配置: <? ...

  9. 《Java Spring框架》Spring切面(AOP)配置详解

    1.  Spring 基本概念 AOP(Aspect Oriented Programming)称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2 ...

随机推荐

  1. StackOverflow 周报 - 与高关注的问题过过招(Java)

    本篇文章是 Stack Overflow 周报的第二周,共收集了 4 道高关注的问题和对应的高赞回答.公众号「渡码」为日更,欢迎关注. DAY1.  serialVersionUID 的重要性 关注: ...

  2. HelloDjango 第 13 篇:分类、归档和标签页

    作者:HelloGitHub-追梦人物 文中涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库 侧边栏已经正确地显示了最新文章列表.归档.分类.标签等信息.现在来完善归档.分类和标签 ...

  3. EAS webservice安全模式

    1.启用安全控制: isRomoteLocate=false 2.请求添加头部: <soapenv:Header> <SessionId xmlns="http://log ...

  4. HDU 1045 Fire Net 二分图建图

    HDU 1045 题意: 在一个n*n地图中,有许多可以挡住子弹的墙,问最多可以放几个炮台,使得炮台不会相互损害.炮台会向四面发射子弹. 思路: 把行列分开做,先处理行,把同一行中相互联通的点缩成一个 ...

  5. 【百度之星】【思维】hdu 6724Totori's Switching Game

    思维题,最后只要判断每个点的度数>=k即可. #pragma comment(linker, "/STACK:1024000000,1024000000") #pragma ...

  6. CF1028C Rectangles 思维

     Rectangles time limit per test 2 seconds memory limit per test 256 megabytes input standard input o ...

  7. Numbers That Count POJ - 1016

    "Kronecker's Knumbers" is a little company that manufactures plastic digits for use in sig ...

  8. springboot的最简创建方式

    springboot是目前比较流行的技术栈之一,我在这里写一个springboot工程最简方式 首先开发工具是IDEA,双击打开IDEA,点击Create new Project 进入到这个页面,选择 ...

  9. POJ 2391 Ombrophobic Bovines(Floyd+二分+最大流)

    题目链接 题意:农场有F(1 <= F <= 200)片草地用于放牛,这些草地有P(1 <= P <= 1500)连接,农场的草地上有一些避雨点,奶牛们可以在避雨点避雨,但是避 ...

  10. Java IO写文件效率

    写入方法: /** *1 按字节写入 FileOutputStream * * @param count 写入循环次数 * @param str 写入字符串 */ public void output ...