您的位置:首页 > 编程语言 > Java开发

Spring学习笔记(三)AOP基本概念

2020-06-28 04:38 477 查看

现在有一个任务需要你处理:你需要给你的项目增加一些非主要的功能例如温馨提示,处理日志。

Class A{
// 执行这个方法的时候需要你增加一些处理日志的功能
public void funA(){
System.out.print("执行方法funA()")
}
public void funB(){
System.out.print("执行方法funB()")
}
public static void main(String[] args) {
try {
funA();
funB();
} catch (Exception e) {
System.out.print("异常")
}
}
}
  • joinPoint
    (连接点)
    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.
    连接点是一个程序运行中的一点,一般代表一个方法的执行,可以通俗的理解funA和funB都是连接点。

  • pointCut
    (切入点)
    a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
    如果要确定对哪个方法增加记录日志的功能,funA还是funB,那我们需要一个条件去确定,这个条件就是切面中的切入表达式(去哪里做事)。切入点就是** 这个被确定的连接点**

  • Advice
    (通知)
    action taken by an aspect at a particular join point. Different types of advice include “around”,“before” and “after” advice.
    通知就是你记录日志这个功能被模块化后在切面中的称呼(切面中的方法,什么时候去做什么事),而通知分为了环绕,前置,后置等通知,它是相对于你执行的时机而言,如果在执行funA之前执行通知方法那就是前置,在之后就是后置。

  • Aspect
    (切面)
    切面就是说将通知,切入点表达式整合的一个模块(什么时候去哪里去做什么事)。

  • Target Object
    (目标对象)
    object being advised by one or more aspects. Also referred to as the advised object.Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.
    目标对象就是指的你用主要执行事务的类创建的对象。

  • Aop Proxy
    (Aop代理对象)
    an object created by the AOP framework in order to implement the aspect contracts(advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy.
    由于目标对象不具有新的功能(或者说目标对象只专注业务逻辑处理),所以需要一个封装了目标对象方法并且织入了通知的对象O来完成写日志+主要事务的功能。而生成的这个对象O用于代理目标对象并称之为代理对象。在Spring框架中这个代理对象可以是JDK动态代理也可以是CGLB代理。

  • Weaving
    (织入)
    linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
    把切面链接到切入点(通知作用到具体连接点)的过程,织入的结果就是:产生了一个融合了目标对象的方法和通知方法的代理对象

  • Introduction
    (引入)

总结:AOP是一种横向抽取思想,并非OOP的纵向继承机制。AOP是基于动态代理的,你可以将一些公共的非主要事务逻辑的代码抽取出来(比如记录日志),实现业务逻辑和非业务逻辑代码的解耦合,提高代码复用性,这样一来你就可以专注于业务逻辑的代码编写,然后通过动态代理的方式在实现业务逻辑的功能同时完成了非业务逻辑的功能(记录日志的功能)。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: