[AOP] 3. Spring AOP中提供的种种Aspects

编程入门 行业动态 更新时间:2024-10-26 00:29:31

[<a href=https://www.elefans.com/category/jswz/34/1767899.html style=AOP] 3. Spring AOP中提供的种种Aspects"/>

[AOP] 3. Spring AOP中提供的种种Aspects

在第一篇文章中,介绍了AOP的一些背景知识以及如何快速上手,然后在第二篇中详细分析了AOP的两种实现 - Spring AOP以及AspectJ。

本文偏向于实践,继续介绍Spring AOP中提供的种种Legacy Aspects。虽然这些Aspects的历史已经比较久远了(好多都是在Spring 1.x时代就存在了),但是并不妨碍我们理解它们背后蕴含的思想以及见识AOP能够解决的问题域。了解这些现成的Aspects,将它们放入我们的工具包,在需要的时候拿出来就能用,而无需重复造轮子;或者将它们有针对性地进行改进,更好地契合我们要解决的问题。

主要会介绍下面几种Aspects,它们都位于包org.springframework.aop.interceptor下:

  1. DebugInterceptor
  2. CustomizableTraceInterceptor
  3. PerformanceMonitorInterceptor
  4. AsyncExecutionInterceptor(下一篇文章中介绍)
  5. ConcurrencyThrottleInterceptor(下一篇文章中介绍)

Spring AOP(Legacy)基本架构

在介绍具体的Aspect实现之前,先来看看Spring AOP(Legacy)的基本架构:

Advice是所有Aspect都会实现的一个接口,它实际上是一个Marker Interface:

/*** Tag interface for Advice. Implementations can be any type* of advice, such as Interceptors.** @author Rod Johnson* @version $Id: Advice.java,v 1.1 2004/03/19 17:02:16 johnsonr Exp $*/
public interface Advice {}

这个接口已经是个很老的接口了,从Spring 1.1就开始存在了。Spring作者亲自操刀的代码哦,其实本文介绍的这些Aspects以及基础类型和接口基本上都有他的身影。

然后在Advice下面,有四个子接口:

  • Interceptor
  • BeforeAdvice
  • AfterAdvice
  • DynamicIntroductionAdvice

为什么要在本小节的标题里面加上一个(Legacy)呢?主要原因在于本文主要会聚焦于第一个Interceptor。它是Spring在未融合AspectJ时,独立创建出来的一套AOP的解决方案,只不过后来应该是作者发现了AspectJ和Spring AOP有不少业务上有重合之处,因此慢慢走在了一起。因此,基于Interceptor的这套方案不妨称它为Legacy Spring AOP。

关于Interceptor这个接口和由它派生出来的类型,大概是这个样子的(蓝色部分是本文会介绍的几个Aspects):

直接继承Advice接口的Interceptor长这样:

/*** This interface represents a generic interceptor.** // ......* This interface is not used directly. Use the sub-interfaces* to intercept specific events.* // ......** @author Rod Johnson* @see Joinpoint*/
public interface Interceptor extends Advice {}

这个Interceptor仍然是个Marker Interface,没有任何实质定义。事实上,Spring一直都在下一盘大棋,所以表现在代码结构上就是预留的扩展点非常多,回过头来看可能结构上有一些臃肿,不够简练。看看2004年和如今2017年,Spring项目的规模差距就知道了。所以从这个意义上而言,学习Spring,主要学习它是如何设计的,如何抽象的。毕竟Spring已经是事实上的JaveEE参考实现了,现如今正统的EJB反倒是无人问津。

这个接口,有2个子接口:

  • ConstructorInterceptor
  • MethodI

更多推荐

[AOP] 3. Spring AOP中提供的种种Aspects

本文发布于:2024-03-05 01:19:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1710938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AOP   Aspects   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!