环境:Spring5.3.23
1. 介绍
今天看Spring文档看到这么一个知识点《Control Flow Pointcuts》都不好翻译
官方原文:
Spring control flow pointcuts are conceptually similar to AspectJ cflow pointcuts, although less powerful. (There is currently no way to specify that a pointcut runs below a join point matched by another pointcut.) A control flow pointcut matches the current call stack. For example, it might fire if the join point was invoked by a method in the com.mycompany.web package or by the SomeCaller class. Control flow pointcuts are specified by using the org.springframework.aop.support.ControlFlowPointcut class.
大意:Spring控制流切入点在概念上类似于aspectj cflow切入点,尽管功能不那么强大。(目前还没有办法指定一个切入点在与另一个切入点匹配的连接点下面运行。)控制流切入点与当前调用堆栈匹配。例如,如果连接点由com.mycompany.web包中的方法或someecaller类调用,则可能会触发该连接点。控制流切入点是通过使用org.springframework.aop.support.ControlFlowPointcut类指定的。
其实看完这个,可能你还是不懂什么意思,接下来我们来跑一个实例,就能明白撒意思了。
2. Control Flow实例
准备几个方法嵌套调用的类
上面的类及方法调用非常简单:PersonManager ---> PersonService ---> PersonDAO。接下来是通过编程的方式创建PersonService代理对象。
控制台输出
从输出的结果发现,在PersonService#save方法之前之前和之后分别打印了日志信息。原理是什么呢?这里我们需要先看ControlFlowPointcut 切入点是如何工作的。
ControlFlowPointcut核心方法
这里只列出了几个重要的方法,在spring中只支持方法级别的拦截。
有了上面源码的分析后,我们再来看看上面的示例代码:
分析到这你应该知道这个Control Flow有撒用了吧,总结:
Control Flow就是用来判断当前执行的线程栈中(所有方法的调用)是否与你给定的类及方法匹配,只有匹配了才能执行我们的增强(通知)代码。
简单说:我PersonService想监控PersonManager中的index方法是否调用了我。
官方有这段说明:
Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account method arguments as well as static information. This means that they must be evaluated with every method invocation and that the result cannot be cached, as arguments will vary.
The main example is the control flow
pointcut.
大意:与静态快捷方式相比,动态快捷方式的评估成本更高。它们会考虑方法参数和静态信息。这意味着每次调用方法时都必须对其进行评估,而且由于参数会发生变化,因此无法缓存评估结果。控制流快捷方式就是一个主要的例子。
3. Control Flow性能
同样来自官方说明:
Control flow pointcuts are significantly more expensive to evaluate at runtime than even other dynamic pointcuts. In Java 1.4, the cost is about five times that of other dynamic pointcuts.
大意:与其他动态切入点相比,控制流切入点在运行时评估的成本要高得多。在Java1.4中,成本大约是其他动态切入点的五倍。
知道了Control Flow怎么一回事,那它有什么使用场景吗?有使用过的还望能分享下,欢迎大家留言讨论。图片