SpringAop英文文档部分翻译

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实例。

猜你喜欢

转载自blog.csdn.net/successA/article/details/85012896