美文网首页
Spring AOP基本概念

Spring AOP基本概念

作者: 一蓬蒿人 | 来源:发表于2020-07-06 14:54 被阅读0次

1.什么是AOP

AOP全称Aspect Oriented Programming,即面向切面编程。主要目的是提供公共的抽象类,减少重复代码的工作成本。

public class ViewSpaceService {
    public void addViewPoint(int pointId) {
        // 事务管理模块
        // 业务处理模块
        // 性能监控模块
    }

    public void deleteViewPoint(int pointId) {
        // 事务管理模块
        // 业务处理模块
        // 性能监控模块
    }
}

若把ViewSpaceService看做树木,业务逻辑便是中间的核心,事务管理和性能监控则是外围的其他同心圆。


横切逻辑示意图

下图更形象描述了通过AOP机制来实现抽象代码复用。


横向抽取

2.Spring AOP

Spring AOP主要基于AspectJ技术,核心采用动态代理机制,在内存中为目标类生成一个代理类,并实现了目标类的所有方法,在代理类的相关方法中进行一些了增强逻辑,同时,回调目标类的真实方法。动态代理有JDK动态代理和CGLib动态代理两种,JDK动态代理的目标类必须实现接口,而CGLib动态代理没有限制;JDK动态代理在创建对象时效率高于CGLib,而运行时效率低于CGLib。

2.1 AOP术语

  • 连接点(Join Point)

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

  • 切面(Aspect)

A modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications.

切面是通知和切入点的结合,Java世界里类是基本元素,所有的事物都必须依托于某个类,切面就是这个类。

3. 实例

参考资料

Spring源码深度解析(AOP功能源码解析)
Spring系列(四):Spring AOP详解)
Spring源码解析系列汇总
完全读懂Spring框架之AOP实现原理
细说Spring——AOP详解(AOP概览)
Spring AOP面向切面编程:理解篇(一看就明白)

相关文章

网友评论

      本文标题:Spring AOP基本概念

      本文链接:https://www.haomeiwen.com/subject/xfjwqktx.html