Aspect Instantiation Models
这是一个高级主题。如果您刚开始使用AOP,可以安全地跳过,以后再学习。 |
This is an advanced topic. If you are just starting out with AOP, you can safely skip it until later. |
默认情况下,在应用程序上下文中每个方面只有一个实例。AspectJ 称之为单例实例化模型。可以定义具有备用生命周期的方面。Spring 支持 AspectJ 的 perthis
、pertarget
和 pertypewithin
实例化模型;percflow
和 percflowbelow
目前不支持。
By default, there is a single instance of each aspect within the application
context. AspectJ calls this the singleton instantiation model. It is possible to define
aspects with alternate lifecycles. Spring supports AspectJ’s perthis
, pertarget
, and
pertypewithin
instantiation models; percflow
and percflowbelow
are not currently
supported.
你可以通过在 @Aspect
注解中指定 perthis
子句来声明一个 perthis
方面。考虑以下示例:
You can declare a perthis
aspect by specifying a perthis
clause in the @Aspect
annotation. Consider the following example:
-
Java
-
Kotlin
@Aspect("perthis(execution(* com.xyz..service.*.*(..)))")
public class MyAspect {
private int someState;
@Before("execution(* com.xyz..service.*.*(..))")
public void recordServiceUsage() {
// ...
}
}
@Aspect("perthis(execution(* com.xyz..service.*.*(..)))")
class MyAspect {
private val someState: Int = 0
@Before("execution(* com.xyz..service.*.*(..))")
fun recordServiceUsage() {
// ...
}
}
在前面的示例中,perthis
子句的效果是为执行业务服务(在切入点表达式匹配的连接点处绑定到 this
的每个唯一对象)的每个唯一服务对象创建一个方面实例。当首次在服务对象上调用方法时,将创建该方面实例。当服务对象超出范围时,该方面也就超出范围了。在创建方面实例之前,它内部的任何建议都不会运行。一旦创建了方面实例,在它内声明的建议将在匹配的连接点运行,但仅当服务对象是该方面与之关联的服务对象时才运行。有关 per
子句的更多信息,请参阅 AspectJ 编程指南。
In the preceding example, the effect of the perthis
clause is that one aspect instance
is created for each unique service object that performs a business service (each unique
object bound to this
at join points matched by the pointcut expression). The aspect
instance is created the first time that a method is invoked on the service object. The
aspect goes out of scope when the service object goes out of scope. Before the aspect
instance is created, none of the advice within it runs. As soon as the aspect instance
has been created, the advice declared within it runs at matched join points, but only
when the service object is the one with which this aspect is associated. See the AspectJ
Programming Guide for more information on per
clauses.
pertarget
实例化模型的工作方式与 perthis
完全相同,但它为匹配连接点处的每个唯一目标对象创建一个方面实例。
The pertarget
instantiation model works in exactly the same way as perthis
, but it
creates one aspect instance for each unique target object at matched join points.