1. What is aspect-oriented programming?
(什么是面向切面编程?)

Aspects help to modularize cross-cutting concerns.
(切面帮助我们模块化横切关注点)
In short, a cross-cutting concern can be described as any functionality that affects multiple points of an application.
(简单来说, 一个横切关注点可以理解为任何影响某个应用程序的功能,这个功能会从一些切入点进入程序)
For example, security is a cross-cutting concern, we cam apply security rules to many methods in an application by AOP.
(举例来说, 安全就是一个横切关注点, 我们可以用过AOP的方式给应用中的许多方法增加安全逻辑)

The below picture can help us understand AOP more intuitively

(下图可以帮助我们更加直观地理解AOP编程)

Spring Core Programming(Spring核心编程) - AOP Concepts(AOP基本概念)_方法调用

2. The benefits of AOP

(AOP的好处)

With AOP, you can define the common functionality in one place,
(通过AOP, 你可以在一个地方定义通用功能)
but you can define how and where this functionality is applied without having to modify the class
to which you’re applying the new feature, thus the class can focus on its main logic.
(你可以通过定义如何并且在何处应用该功能,而不用修改要被影响的那个类,这样被应用的类可以关注它的主逻辑)

 

3. Some core concepts of AOP

   (AOP的一些核心概念)

Below are the important terminologies of aspects:
(以下是一些切面的重要术语)

advice(通知) / pointcuts(切点) / join points(连接点)

直观如如下:

Spring Core Programming(Spring核心编程) - AOP Concepts(AOP基本概念)_sed_02

 

3-1) advice(通知)
The job of an aspect is called advice,
(通知其实就是切面的工作)
it defines what and when of an aspect.
(它定义了这个切面干什么的,以及何时使用)

Spring aspects can work with five kinds of advice:
(Spring中可以有5种类型的通知)

* Before(前置通知)
— The advice functionality takes place before the advised method is invoked.
(在目标方法被调用之前调用)
* After(后置通知)
— The advice functionality takes place after the advised method completes, regardless of the outcome.
(在目标方法完成之后调用, 不关心方法的输出)
* After-returning(返回通知)
— The advice functionality takes place after the advised method successfully completes.
(在目标方法成功执行之后调用)
* After-throwing(异常通知)
— The advice functionality takes place after the advised method throws an exception.
(在目标方法抛出异常后调用)
* Around(环绕通知)
— The advice wraps the advised method, providing some functionality before and after the advised method is invoked.
(包裹目标方法, 在目标方法调用之前和调用之后都要调用)

 

3-2) JOIN POINTS(切点)
A join point is a point in the execution of the application where an aspect can be plugged in.
(连接点是在应用执行过程中插入的点)
could be a method being called, an exception being thrown, or even a field being modified
(可以使调用方法时, 异常抛出时, 或者甚至是一个字段被修改时)

3-3) POINTCUTS(切点)
If advice defines the what and when of aspects, then pointcuts define the where.
(如果说通知定义了切面的什么和何时的话,那么切点定义了切面的何处)
Specify pointcuts using explicit class and method names
or through regular expressions that define matching class and method name patterns.
(通过制定类和方法名,或者正则表达式指定的类和方法名称来指定切点)

 

4. SPRING ADVISES OBJECTS AT RUNTIME
(Spring在运行时通知对象)

In Spring, aspects are woven into Spring-managed beans at runtime by wrapping them with a proxy class.
(通过在代理类中包裹切面, Spring在运行时把切面织人到Spring管理的类中)

如下图:

Spring Core Programming(Spring核心编程) - AOP Concepts(AOP基本概念)_方法调用_03

 

技术改变世界