SpringAop英文文件部分翻譯

ZeroWM發表於2018-12-15

SpringFrameWork

 

5. Aspect Oriented Programming with Spring

5.1. AOP Concepts

5.2. Spring AOP Capabilities and Goals

5.3. AOP Proxies

5.4. @AspectJ support

5.5. Schema-based AOP Support

5.6. Choosing which AOP Declaration Style to Use

5.7. Mixing Aspect Types

5.8. Proxying Mechanisms

5.9. Programmatic Creation of @AspectJ Proxies

5.10. Using AspectJ with Spring Applications

5.11. Further Resources

 

原文地址:

https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#aop-ataspectj

 

5. Aspect Oriented Programming with Spring

Aspect-oriented Programming (AOP) complements Object-oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns (such as transaction management) that cut across multiple types and objects. (Such concerns are often termed “crosscutting” concerns in AOP literature.)

面向切面的程式設計是對物件導向程式設計的一種補充,它提供了另外一種關於程式架構的思想。物件導向的程式設計核心模組是類,然而在AOP中核心模組是切面。切面實現了多種型別和物件的模組化,比如事物的管理。

One of the key components of Spring is the AOP framework. While the Spring IoC container does not depend on AOP (meaning you do not need to use AOP if you don’t want to), AOP complements Spring IoC to provide a very capable middleware solution.

Spring AOP框架是Spring 的關鍵元件。然而IOC容器是不依賴AOP的,AOP是對IOC的補充,提供了非常強大的中介軟體解決方案。

 

 

AOP is used in the Spring Framework to:

AOP應用在Spring框架的以下方面:

  • Provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management.
  • 提供了企業級別的宣告式服務,尤其是作為EJB宣告服務的替代品。最重要的服務是宣告式事物管理。
  • Let users implement custom aspects, complementing their use of OOP with AOP.
  • AOP讓使用者實現了自定義切面,並且對OOP應用做了補充。

 

5.1. AOP Concepts

Let us begin by defining some central AOP concepts and terminology. These terms are not Spring-specific. Unfortunately, AOP terminology is not particularly intuitive. However, it would be even more confusing if Spring used its own terminology.

讓我們從定義AOP的核心概念和術語開始。這些術語不是專屬Spring的。遺憾是,AOP的屬於不是特別的直觀。不過如果Spring使用它本身的術語會更加的讓人難以理解。

  • 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. In Spring AOP, aspects are implemented by using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style)
  • Aspect:橫切多個類的模組概念。在企業基本的應用中,事物的管理是最好的橫切概念引用的例子。在Spring AOP中,切面通過xml配置常規類,或者給常規類新增@Aspect註解來實現。
  • 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.
  • Join point:執行程式中的一個點,比如執行一個方法或者捕獲一次異常。在Spring AOP中,一個連線點經常代表一個方法的執行。
  • Advice: Action taken by an aspect at a particular join point. Different types of advice include “around”, “before” and “after” advice. (Advice types are discussed later.) Many AOP frameworks, including Spring, model an advice as an interceptor and maintain a chain of interceptors around the join point.
  • Advice:一個切面在連線點的特殊行為,Advice包含多種型別,包括aroundbeforeafter三種。很多AOP框架,包括Spring,把advice比作攔截器,它確保攔截器鏈圍繞join point
  • 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.
  • Pointcut: Pointcut是匹配join points的動作。Advice是跟切入點表示式相關聯的,它在任意匹配切點的join point處執行。跟切入點表示式匹配的join pointAOP的核心。Spring採用AspectJ切入點表示式作為預設表示式。
  • Introduction: Declaring additional methods or fields on behalf of a type. Spring AOP lets you introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)
  • Introduction:宣告額外的方法或者欄位,代表一種型別。Spring AOP允許您像任意物件引入新介面。舉個例子,您可以使用Introduction建立一個bean去實現IsModified介面,來簡化快取。
  • Target object: An object being advised by one or more aspects. Also referred to as the “advised object”. Since Spring AOP is implemented by using runtime proxies, this object is always a proxied object.
  • Target object:一個擁有一個或者多個切面的物件,常被稱為advised object。因為Spring AOP是通過動態代理實現的,這個物件經常被稱為被代理物件。
  • AOP proxy: 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 is a JDK dynamic proxy or a CGLIB proxy.
  • AOP proxy: AOP框架建立物件用於實現aspect契約。在spring框架中,aop代理是jdk動態代理或者cblib代理。
  • 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.
  • Weaving:通過其他應用型別或者物件連線切面,建立一個建議物件。編譯過程中就已經被執行,載入時間或者運營時時間。Spring AOP,像其他的純粹的Java AOP框架,在執行時進行編織。

Spring AOP includes the following types of advice:

Spring AOP包含以下型別的advice

  • Before advice: Advice that runs before a join point but that does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  • Before advice:在連線點join point處執行,但是不能阻止已經進入連線點join point的流程。
  • After returning advice: Advice to be run after a join point completes normally (for example, if a method returns without throwing an exception).
  • After returning advice: Advice在連線點join point正常完成之後執行。
  • After throwing advice: Advice to be executed if a method exits by throwing an exception.
  • After throwing advice: Advice在方法丟擲異常之後執行。
  • After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).
  • After (finally) advice:無論連線點join point是正常還是異常退出,Advice都會被執行。
  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.
  • Around advice:Advice圍繞連線點join point ,就像方法的呼叫。這是最強大的adviceAround advice在方法呼叫前後進行自定義方法。它是負責選擇執行join point接入點,還是快速選擇方法執行:通過返回值或者丟擲異常。

Around advice is the most general kind of advice. Since Spring AOP, like AspectJ, provides a full range of advice types, we recommend that you use the least powerful advice type that can implement the required behavior. For example, if you need only to update a cache with the return value of a method, you are better off implementing an after returning advice than an around advice, although an around advice can accomplish the same thing. Using the most specific advice type provides a simpler programming model with less potential for errors. For example, you do not need to invoke the proceed() method on the JoinPoint used for around advice, and, hence, you cannot fail to invoke it.

Around advice是最常用的advice。由於Spring AOP(如AspectJ)提供了全方位的advice型別,因此我們建議您使用可以實現所需行為的最小的有效的建議型別。例如,如果您只需要使用方法的返回值更新快取,那麼最好在實現after returning advice而不是around advice,儘管around advice可以完成同樣的事情。使用最具體的advice型別可以提供更簡單的程式設計模型,減少錯誤的可能性。例如,您不需要在用於around advice JoinPoint上呼叫proceed()方法,因此,您不能不呼叫它。

The concept of join points matched by pointcuts is the key to AOP, which distinguishes it from older technologies offering only interception. Pointcuts enable advice to be targeted independently of the object-oriented hierarchy. For example, you can apply an around advice providing declarative transaction management to a set of methods that span multiple objects (such as all business operations in the service layer).

Join points匹配的pointcutsAOP的關鍵,舊技術只使用了攔截器,這是區分新舊技術的關鍵。Pointcuts確保advice可以獨立於物件導向的層次結構。例如,您可以將一個提供宣告式事務管理around advice應用於跨多個物件(例如服務層中的所有業務操作)的一組方法

 

 

5.2. Spring AOP Capabilities and Goals

Spring AOP is implemented in pure Java. There is no need for a special compilation process. Spring AOP does not need to control the class loader hierarchy and is thus suitable for use in a servlet container or application server.

Spring AOP是純java實現的。不需要特殊的編譯過程。Spring AOP不需要控制類載入器層次結構,因此適合在servlet容器或應用程式伺服器中使用。

Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans). Field interception is not implemented, although support for field interception could be added without breaking the core Spring AOP APIs. If you need to advise field access and update join points, consider a language such as AspectJ.

Spring AOP目前僅支援方法執行連線點join points(建議在Spring bean上執行方法)。雖然可以在不破壞核心Spring AOP API的情況下新增對欄位攔截的支援,但未實現欄位攔截。如果您需要建議欄位訪問和更新連線點join points,請考慮使用AspectJ等語言。

 

Spring AOP’s approach to AOP differs from that of most other AOP frameworks. The aim is not to provide the most complete AOP implementation (although Spring AOP is quite capable). Rather, the aim is to provide a close integration between AOP implementation and Spring IoC, to help solve common problems in enterprise applications.

Spring AOPAOP方法與大多數其他AOP框架的方法不同。目的不是提供最完整的AOP實現(儘管Spring AOP非常強大)。相反,目標是在AOP實現和Spring IoC之間提供緊密整合,以幫助解決企業應用程式中的常見問題。

Thus, for example, the Spring Framework’s AOP functionality is normally used in conjunction with the Spring IoC container. Aspects are configured by using normal bean definition syntax (although this allows powerful “auto-proxying” capabilities). This is a crucial difference from other AOP implementations. You cannot do some things easily or efficiently with Spring AOP, such as advise very fine-grained objects (typically, domain objects). AspectJ is the best choice in such cases. However, our experience is that Spring AOP provides an excellent solution to most problems in enterprise Java applications that are amenable to AOP.

因此,例如,Spring FrameworkAOP功能通常與Spring IoC容器一起結合使用。通過使用普通bean定義語法來配置方面(儘管這允許強大的“auto-proxying”功能)。這是與其他AOP實現的關鍵區別。使用Spring AOP無法輕鬆或高效地完成某些操作,例如建議非常細粒度的物件(通常是域物件)。在這種情況下,AspectJ是最佳選擇。但是,我們的經驗是,Spring AOP為適合AOP的企業Java應用程式中的大多數問題提供了出色的解決方案。

Spring AOP never strives to compete with AspectJ to provide a comprehensive AOP solution. We believe that both proxy-based frameworks such as Spring AOP and full-blown frameworks such as AspectJ are valuable and that they are complementary, rather than in competition. Spring seamlessly integrates Spring AOP and IoC with AspectJ, to enable all uses of AOP within a consistent Spring-based application architecture. This integration does not affect the Spring AOP API or the AOP Alliance API. Spring AOP remains backward-compatible. See the following chapter for a discussion of the Spring AOP APIs.

Spring AOP從未努力與AspectJ競爭,以提供全面的AOP解決方案。我們相信,基於代理的框架(如Spring AOP)和完整的框架(如AspectJ)都很有價值,而且它們是互補的,而不是競爭。 SpringSpring AOPIoCAspectJ無縫整合,以在一致的基於Spring的應用程式架構中實現AOP的所有使用。此整合不會影響Spring AOP APIAOP Alliance API Spring AOP仍然向後相容。

 

5.3. AOP Proxies

Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies. This enables any interface (or set of interfaces) to be proxied.

Spring AOP預設使用AOP代理的標準JDK動態代理。這使得任何介面(或介面集)都可以被代理。

Spring AOP can also use CGLIB proxies. This is necessary to proxy classes rather than interfaces. By default, CGLIB is used if a business object does not implement an interface. As it is good practice to program to interfaces rather than classes, business classes normally implement one or more business interfaces. It is possible to force the use of CGLIB, in those (hopefully rare) cases where you need to advise a method that is not declared on an interface or where you need to pass a proxied object to a method as a concrete type.

Spring AOP也可以使用CGLIB代理。這是代理類而不是介面所必需的。預設情況下,如果業務物件未實現介面,則使用CGLIB。由於優化的做法是程式設計介面而不是類,業務類通常實現一個或多個業務介面。可以強制使用CGLIB,在那些需要建議未在介面上宣告的方法或需要將代理物件作為具體型別傳遞給方法的情況下(希望很少見)。

It is important to grasp the fact that Spring AOP is proxy-based. See Understanding AOP Proxies for a thorough examination of exactly what this implementation detail actually means.

 掌握Spring AOP是基於代理的這一事實非常重要。請參閱瞭解AOP代理,以全面瞭解此實現細節的實際含義。

5.4. @AspectJ support

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with annotations. The @AspectJ style was introduced by the AspectJ project as part of the AspectJ 5 release. Spring interprets the same annotations as AspectJ 5, using a library supplied by AspectJ for pointcut parsing and matching. The AOP runtime is still pure Spring AOP, though, and there is no dependency on the AspectJ compiler or weaver.

5.4.2. Declaring an Aspect

With @AspectJ support enabled, any bean defined in your application context with a class that is an @AspectJ aspect (has the @Aspect annotation) is automatically detected by Spring and used to configure Spring AOP. The next two examples show the minimal definition required for a not-very-useful aspect.

在啟用@AspectJ支援的情況下,在應用程式上下文中定義的任何bean都具有@AspectJ方面的類(具有@Aspect註釋),S​​pring會自動檢測並用於配置Spring AOP。接下來的兩個示例顯示了非常有用的方面所需的最小定義。 

The first of the two example shows a regular bean definition in the application context that points to a bean class that has the @Aspect annotation:


這兩個示例中的第一個示例在應用程式上下文中顯示了一個常規bean定義,該定義指向具有@Aspect批註的bean類:

<bean id="myAspect" class= "org.xyz.NotVeryUsefulAspect">   
<!-- configure properties of the aspect here -->
</bean>

 

Aspects (classes annotated with @Aspect) can have methods and fields, the same as any other class. They can also contain pointcut, advice, and introduction (inter-type) declarations.

Aspect註釋的類)可以包含方法和欄位,與任何其他類相同。它們還可以包含切入點,advice和引入(型別間)宣告。

通過元件掃描自動檢測方面
您可以在Spring XML配置中將方面類註冊為常規bean,或者通過類路徑掃描自動檢測它們 - 與任何其他Spring管理的bean相同。但是,請注意@Aspect註釋不足以在類路徑中進行自動檢測。為此,您需要新增一個單獨的@Component註釋(或者,根據Spring的元件掃描程式的規則,可以使用符合條件的自定義構造型註釋)。

與其他方面的方面建議? 
Spring AOP中,aspects本身不能成為其他方面的建議目標。類上的@Aspect註釋將其標記為aspect,因此將其從自動代理中排除。

5.4.3. Declaring a Pointcut

Pointcuts determine join points of interest and thus enable us to control when advice executes. Spring AOP only supports method execution join points for Spring beans, so you can think of a pointcut as matching the execution of methods on Spring beans. A pointcut declaration has two parts: a signature comprising a name and any parameters and a pointcut expression that determines exactly which method executions we are interested in. In the @AspectJ annotation-style of AOP, a pointcut signature is provided by a regular method definition, and the pointcut expression is indicated by using the @Pointcut annotation (the method serving as the pointcut signature must have a void return type).

Pointcuts確定感興趣的連線點,從而使我們能夠控制advice何時執行。 Spring AOP僅支援Spring bean的方法執行連線點,因此您可以將切入點視為匹配Spring bean上方法的執行。切入點宣告有兩個部分:一個包含名稱和任何引數的簽名,以及一個精確確定我們感興趣的方法執行的切入點表示式。在AOP
@AspectJ註釋樣式中,切入點簽名由常規方法定義提供,並使用
Pointcut註釋指示切入點表示式(用作切入點簽名的方法必須具有void返回型別)。 

An example may help make this distinction between a pointcut signature and a pointcut expression clear. The following example defines a pointcut named anyOldTransfer that matches the execution of any method named transfer:

一個示例可以幫助區分切入點簽名和切入點表示式。以下示例定義名為anyOldTransfer的切入點,該切入點與名為transfer的任何方法的執行相匹配:

@Pointcut("execution(* transfer(..))")
// the pointcut expression
private void anyOldTransfer() {}
// the pointcut signature

The pointcut expression that forms the value of the @Pointcut annotation is a regular AspectJ 5 pointcut expression. For a full discussion of AspectJ’s pointcut language, see the AspectJ Programming Guide (and, for extensions, the AspectJ 5 Developer’s Notebook) or one of the books on AspectJ (such as Eclipse AspectJ, by Colyer et. al., or AspectJ in Action, by Ramnivas Laddad).

@Pointcut註釋值的切入點表示式是常規的AspectJ 5切入點表示式。有關AspectJ的切入點語言的完整討論,請參閱AspectJ程式設計指南(以及,對於擴充套件,AspectJ 5開發人員的筆記本)或AspectJ上的一本書(例如Eclipse AspectJColyer等人,或AspectJ in Action ,作者:Ramnivas Laddad)。

Supported Pointcut Designators

Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut expressions:

Spring AOP支援以下AspectJ切入點指示符(PCD)用於切入點表示式:

  • execution: For matching method execution join points. This is the primary pointcut designator to use when working with Spring AOP.
  • execution:用於匹配方法執行連線點。這是使用Spring AOP時使用的主要切入點指示符。
  • within: Limits matching to join points within certain types (the execution of a method declared within a matching type when using Spring AOP).
  • this: Limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type.
  • target: Limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type.
  • args: Limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types.
  • @target: Limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type.
  • @args: Limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given types.
  • @within: Limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP).
  • @annotation: Limits matching to join points where the subject of the join point (the method being executed in Spring AOP) has the given annotation.

Other pointcut types

The full AspectJ pointcut language supports additional pointcut designators that are not supported in Spring: callgetsetpreinitializationstaticinitializationinitializationhandleradviceexecutionwithincodecflow,cflowbelowif@this, and @withincode. Use of these pointcut designators in pointcut expressions interpreted by Spring AOP results in an IllegalArgumentException being thrown.

The set of pointcut designators supported by Spring AOP may be extended in future releases to support more of the AspectJ pointcut designators.

Because Spring AOP limits matching to only method execution join points, the preceding discussion of the pointcut designators gives a narrower definition than you can find in the AspectJ programming guide. In addition, AspectJ itself has type-based semantics and, at an execution join point, both this and target refer to the same object: the object executing the method. Spring AOP is a proxy-based system and differentiates between the proxy object itself (which is bound to this) and the target object behind the proxy (which is bound to target).

 

Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are, by definition, not intercepted. For JDK proxies, only public interface method calls on the proxy can be intercepted. With CGLIB, public and protected method calls on the proxy are intercepted (and even package-visible methods, if necessary). However, common interactions through proxies should always be designed through public signatures.

Note that pointcut definitions are generally matched against any intercepted method. If a pointcut is strictly meant to be public-only, even in a CGLIB proxy scenario with potential non-public interactions through proxies, it needs to be defined accordingly.

If your interception needs include method calls or even constructors within the target class, consider the use of Spring-driven native AspectJ weaving instead of Spring’s proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving before making a decision.

 

The idOrNameOfBean token can be the name of any Spring bean. Limited wildcard support that uses the * character is provided, so, if you establish some naming conventions for your Spring beans, you can write a bean PCD expression to select them. As is the case with other pointcut designators, the bean PCD can be used with the && (and), || (or), and ! (negation) operators, too.

 

The bean PCD is supported only in Spring AOP and not in native AspectJ weaving. It is a Spring-specific extension to the standard PCDs that AspectJ defines and is, therefore, not available for aspects declared in the @Aspect model.

The bean PCD operates at the instance level (building on the Spring bean name concept) rather than at the type level only (to which weaving-based AOP is limited). Instance-based pointcut designators are a special capability of Spring’s proxy-based AOP framework and its close integration with the Spring bean factory, where it is natural and straightforward to identify specific beans by name.


5.4.4. Declaring Advice

Advice is associated with a pointcut expression and runs before, after, or around method executions matched by the pointcut. The pointcut expression may be either a simple reference to a named pointcut or a pointcut expression declared in place.

Advice與切入點表示式相關聯,並在切入點匹配的方法執行之前,之後或周圍執行。切入點表示式可以是對命名切入點的簡單引用,也可以是在適當位置宣告切入點表示式。

 

Around Advice

The last kind of advice is around advice. Around advice runs “around” a matched method’s execution. It has the opportunity to do work both before and after the method executes and to determine when, how, and even if the method actually gets to execute at all. Around advice is often used if you need to share state before and after a method execution in a thread-safe manner (starting and stopping a timer, for example). Always use the least powerful form of advice that meets your requirements (that is, do not use around advice if before advice would do).

最後一種advicearound advicearound advice圍繞匹配方法的執行執行。它有機會在方法執行之前和之後完成工作,並確定何時,如何,甚至方法實際上都可以執行。如果您需要以執行緒安全的方式(例如,啟動和停止計時器)在方法執行之前和之後共享狀態,則通常會使用Around advice。始終使用滿足要求的最小的有效的advice形式(即,如果before advice可以使用,請不要使用around advice)。

Around advice is declared by using the @Around annotation. The first parameter of the advice method must be of type ProceedingJoinPoint. Within the body of the advice, calling proceed() on the ProceedingJoinPoint causes the underlying method to execute. The proceed method can also pass in an Object[]. The values in the array are used as the arguments to the method execution when it proceeds.

Around advice宣告一個@Around註解 advice方法的第一個引數必須是ProceedingJoinPoint型別。在通知的主體內,在ProceedingJoinPoint上呼叫proceed()會導致執行底層方法。 proceed方法也可以傳入Object []。陣列中的值在進行時用作方法執行的引數。

 

 

Advice Ordering

What happens when multiple pieces of advice all want to run at the same join point? Spring AOP follows the same precedence rules as AspectJ to determine the order of advice execution. The highest precedence advice runs first “on the way in” (so, given two pieces of before advice, the one with highest precedence runs first). “On the way out” from a join point, the highest precedence advice runs last.

當多個advice都想在同一個連線點執行時會發生什麼? Spring AOP遵循與AspectJ相同的優先順序規則來確定advice執行的順序。最高優先順序的advice首先“on the way”(因此,給定兩條之前的建議,優先順序最高的建議首先執行)。從連線點On the way out,最高優先順序advice最後執行。

When two pieces of advice defined in different aspects both need to run at the same join point, unless you specify otherwise, the order of execution is undefined. You can control the order of execution by specifying precedence. This is done in the normal Spring way by either implementing the org.springframework.core.Ordered interface in the aspect class or annotating it with the Order annotation. Given two aspects, the aspect returning the lower value from Ordered.getValue() (or the annotation value) has the higher precedence.

當在不同方面定義的兩個advice都需要在同一個連線點執行時,除非另外指定,否則執行順序是未定義的。您可以通過指定優先順序來控制執行順序。這是通過在方法類中實現org.springframework.core.Ordered介面或使用Order註解對其進行註釋來以常規Spring方式完成的。給定兩個方面,從Ordered.getValue()(或註釋值)返回較低值的方面具有較高的優先順序。 

When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined (since there is no way to retrieve the declaration order through reflection for javac-compiled classes). Consider collapsing such advice methods into one advice method per join point in each aspect class or refactor the pieces of advice into separate aspect classes that you can order at the aspect level.

當在同一aspect定義的兩個advice都需要在同一個連線點執行時,排序是未定義的(因為沒有辦法通過反射為javac編譯的類檢索宣告順序)。考慮將這些建議方法摺疊到每個方面類中每個連線點的一個建議方法中,或者將這些建議重構為可以在aspect級別訂購的單獨aspect類。

5.4.6. Aspect Instantiation Models

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 and pertarget instantiation models ( percflow, percflowbelow, and pertypewithinare not currently supported).

 預設情況下,應用程式上下文中的每個aspect都有一個例項。 AspectJ將其稱為單例例項化模型。可以使用備用生命週期定義aspect Spring支援AspectJperthispertarget例項化模型(目前不支援percflowpercflowbelowpertypewithin

You can declare a perthis aspect by specifying a perthis clause in the @Aspect annotation. Consider the following example:

@Aspect("perthis(com.xyz.myapp.SystemArchitecture.businessService())")
public class MyAspect{    
private int someState;@Before(com.xyz.myapp.SystemArchitecture.businessService())
public void recordServiceUsage() {        // ...}}

In the preceding example, the effect of the 'perthis' clause is that one aspect instance is created for each unique service object that executes 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 executes. As soon as the aspect instance has been created, the advice declared within it executes 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.

在前面的示例中,'perthis'子句的作用是為執行業務服務的每個唯一服務物件建立一個aspect例項(每個唯一物件在由切入點表示式匹配的連線點處繫結到'this')。aspect例項是在第一次在服務物件上呼叫方法時建立的。當服務物件超出範圍時,該aspect超出範圍。在建立aspect例項之前,其中沒有任何advice執行。一旦建立了aspect例項,在其中宣告的通知就會在匹配的連線點處執行,但僅在服務物件與此aspect關聯的服務物件時執行。有關per子句的更多資訊,請參閱AspectJ程式設計指南。

 

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.

pertarget例項化模型的工作方式與perthis完全相同,但它為匹配的連線點處的每個唯一目標物件建立一個aspect例項。

相關文章