Aspect-oriented Programming (AOP) 補充了Object-oriented Programming (OOP)。OOP最重要的概念模塊是類(class),而AOP中則是切面。AOP能夠在多種類型和多個類間進行操做,能夠認爲AOP串起了這些數據。OOP使用封裝,繼承和多態來定義對象層級的結構,OOP容許用戶定義縱向層級的關係,可是對於橫向層級的關係,好比日誌功能,日誌老是橫向分佈在代碼中,和對象的核心功能沒有關係。其餘如安全性和異常處理也是同樣,這種橫向分佈的和核心對象功能無關的代碼稱爲橫切(aspect)。java
在OOP中,實現橫切功能每每須要大量重複的代碼。而AOP中可使用橫切來剖開對象內部,將影響多個類的公共行爲抽象到尾一個可重用模塊,稱爲aspect。ios
1.AOP Conceptsgit
AOP中的概念和定義程序員
Aspect: 一個能夠穿插多個類的模塊概念。事物管理就是一個典型的AOP例子。Spring使用常規類或者@Aspect註解的類來實現Aspect。web
Join point: 程序執行過程當中的一個點,好比方法的執行或者異常的處理。Spring AOP中,切入點指的是方法的執行。spring
Advice: Aspect在切入點執行的操做。Advice包括「around」, 「before」和「after」 三種類型。express
Introduction: 在不影響類代碼的前提下,在運行期動態的爲類添加方法或者字段。bootstrap
Target object: 被一個或者多個切面通知的對象,也能夠稱爲通知對象。Spring AOP是運行時代理來實現的,因此這個對象用因而被代理的。緩存
AOP proxy:AOP建立的用於實現切面(通知方法執行之類的)的對象。AOP是JDK動態代理或者CGLIB代理。tomcat
Weaving: 將切面和應用的其餘類型或者對象鏈接來建立通知對象。這一步驟能夠在編譯,代碼加載,或者運行時完成(AOP在運行時完成)。
Point cut:對鏈接點(Join point)進行攔截的定義。
Spring AOP advice的類型:
Before advice: 在切入點以前運行的advice,不能阻止aop繼續進行織入操做。
After returning advice: 在切入點正常完成以後運行的advice(好比一個沒有拋出異常的方法)。
After throwing advice: 在方法拋出異常以後執行的advice。
After (finally) advice: 方法完成後執行的advice(無論方法正常運行或者拋出異常)。
Around advice: 圍繞切入點運行的advice好比方法的調用。最強力的advice就是around advice。around advice能夠在方法調用前和調用後執行經常使用操做。around advice還負責選擇繼續執行切入點或者經過放回本身的返回值或拋出異常來中止切入點的執行。
Spring官方建議使用能知足要求的advice就能夠了,不須要老是使用功能強大的advice類型。好比須要在方法返回的時候更新緩存,使用after advice要比使用around advice更穩當,使用功能更適合的advice能夠防止潛在的錯誤而且能夠精簡代碼。
程序員使用AOP通常分爲三個步驟:
①.實現基本業務代碼
②.定義切入點,切入點能夠橫切
③.定義加強處理,即AOP爲不一樣業務織入得處理動做
2.AOP Proxies
Spring AOP默認使用標準JDK動態代理實現AOP代理器,這保證任何接口均可以被代理。若是被代理的不是接口類,則會切換到CGLIB代理。
3.@AspectJ support
3.1.Enabling @AspectJ Support
可使用XML配置或者Java代碼的方式配置@AspectJ支持。
Java註解的方式使用@AspectJ
使用@EnableAspectJAutoProxy註解開啓@AspectJ支持,如如下示例:
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
}
在Spring框架的配置文件中配置aop:aspectj-autoproxy元素也能夠開啓@AspectJ代理支持:
3.2.Declaring an Aspect
開啓@AspectJ註解支持後,任何使用@Aspect註解的類都會被Spring自動檢測而且被用於配置AOP。
如下是兩個簡單的aspect例子:
package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class NotVeryUsefulAspect {
}
@Aspect註釋的類不能被自動檢測,須要添加額外的@Component註解才能被IOC掃描到。
Aspect類不能被其餘Aspect類切入,AOP會將其從自動代理中排除,由於他被標記爲一個aspect。
3.Declaring a Pointcut
Pointcut決定aspect須要在哪裏執行通知(advice)的操做,Spring中可使用註解或者xml配置文件的方式。
使用註解定義Pointcut:
@Pointcut("execution(* transfer(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signature
3.1.Supported Pointcut Designators
Spring AOP支持在@Aspect註解中使用以下標記:
匹配方法的指示器(designator)
execution:定義切入點匹配的方法,AOP將advice進行織入,完成對於被代理對象的加強操做。
匹配註解的指示器
@targer()
@args()
@within()
@annotation()
匹配包和類型
within()
//匹配ProduceService中的全部方法
@Pointcut("within(com.imooc.service.ProduceService)")
public void matchType(){...}
//匹配com.imooc包及子包下全部類的方法
@Pointcut("within(com.imooc..*)")
public void matchPackage(){...}
匹配對象
this()
bean()
target()
匹配參數
args()
Other pointcut types
功能徹底的AspectJ切入點支持Spring中不支持的切入點:call, get, set, preinitialization, staticinitialization, initialization, handler, adviceexecution, withincode, cflow, cflowbelow, if, @this, and @withincode. 在Spring AOP中使用這些切入點會拋出IllegalArgumentException異常。
3.2.Sharing Common Pointcut Definitions
execution表達式:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern)
throws-pattern?)
修飾符匹配(modifier-pattern?)
返回值匹配(ret-type-pattern)能夠爲表示任何返回值,全路徑的類名等
類路徑匹配(declaring-type-pattern?)
方法名匹配(name-pattern)能夠指定方法名 或者 表明全部, set* 表明以set開頭的全部方法
參數匹配((param-pattern))能夠指定具體的參數類型,多個參數間用「,」隔開,各個參數也能夠用「」來表示匹配任意類型的參數,如(String)表示匹配一個String參數的方法;(,String) 表示匹配有兩個參數的方法,第一個參數能夠是任意類型,而第二個參數是String類型;能夠用(..)表示零個或多個任意參數
異常類型匹配(throws-pattern?)
其中後面跟着「?」的是可選項,除了返回類型模板ret-type-pattern外都是可選項。表示通配符,()匹配無參數方法,(...)匹配任意參數(零個或者多個)方法,
()匹配任意一個任意類型參數的方法,(*,String)表示第一個參數隨意,第二個參數必須是String類型。
execution經常使用示例:
切入點匹配任意公共方法
execution(public * *(..))
切入點匹配任意set開頭的方法
execution(* set*(..))
切入點匹配com.xyz.service.AccountService接口定義的全部方法
execution(* com.xyz.service.AccountService.*(..))
切入點匹配任何定義在com.xyz.service中的方法
execution(* com.xyz.service..(..))
切入點匹配任何定義在com.xyz.service和其子包的方法
execution(* com.xyz.service...(..))
任何在com.xyz.service包中的參與點(方法):
within(com.xyz.service.*)
任何在com.xyz.service和其子包中的參與點(方法):
within(com.xyz.service..*)
任何com.xyz.service.AccountService接口定義的參與點(方法):
this(com.xyz.service.AccountService)
任何實現了AccountService接口的target object:
target(com.xyz.service.AccountService)
任何有單個參數而且參數可序列化的鏈接點(方法):
args(java.io.Serializable)
任何目標類加了@Transactional註解的鏈接點(方法):
@target(org.springframework.transaction.annotation.Transactional)
任何代理對象類型加了@Transactional註解的鏈接點:
@within(org.springframework.transaction.annotation.Transactional)
任何使用@Transactional註解了執行方法的鏈接點:
@annotation(org.springframework.transaction.annotation.Transactional)
任何帶有一個@Classified 註解入參的鏈接點:
@args(com.xyz.security.Classified)
鏈接點名稱爲tradeService:
bean(tradeService)
鏈接點名稱匹配Service:
bean(Service)
3.3.Writing Good Pointcuts
現有的指示器可分爲三種:
分類指示器將指示器分紅特定的類型:execution, get, set, call, and handler
生命週期指示器將指示器按照其做用範圍分類:within and withincode
上下文指示器將指示器按照上下文分類:this,target,@annotation
一個比較好的鏈接點必須至少含有前兩種指示器,只有一種指示器也不會影響功能但會增長織入操做的時間和內存消耗。
3.4. Declaring Advice
Advice和切入點(join point)緊密聯繫,其在鏈接點方法執行以前,以後或者環繞(以前及以後)執行。Advice能夠匹配一個明確的鏈接點或者
Before Advice
可使用 @Before註解定義before advice:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class BeforeExample {
@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doAccessCheck() { // ... }
}
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class BeforeExample {
@Before("execution(* com.xyz.myapp.dao.*.*(..))") public void doAccessCheck() { // ... }
}
After Returning Advice
可使用@AfterReturning註解定義after advice:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
public class AfterReturningExample {
@AfterReturning("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doAccessCheck() { // ... }
}
有些狀況下可能須要在@AfterReturning中訪問被代理方法的返回值,可使用returning屬性定義返回值,被代理方法中的返回值要和returning定義的一直才能保證對應的advice能夠獲取到被代理方法的返回值:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
public class AfterReturningExample {
@AfterReturning( pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()", returning="retVal") public void doAccessCheck(Object retVal) { // ... }
}
After Throwing Advice
可使用@AfterThrowing來定義一個after throwing advice,其在被代理方法拋出異常後開始執行:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
public class AfterThrowingExample {
@AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doRecoveryActions() { // ... }
}
可使用throwing屬性來獲取被代理方法拋出的異常,拋出的異常引用字段名稱和類型必須和throwing定義的一致:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
public class AfterThrowingExample {
@AfterThrowing( pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()", throwing="ex") public void doRecoveryActions(DataAccessException ex) { // ... }
}
After (Finally) Advice
使用@After聲明的after advice在被代理方法執行完退出後執行(正常退出或者拋出異常),通常用於釋放資源:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
@Aspect
public class AfterFinallyExample {
@After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doReleaseLock() { // ... }
}
Around Advice
around advice用於在被代理方法執行前和執行後進行操做,同時其還決定被代理方法什麼時候,如何以及是否執行。通常狀況下使用符合要求的advice就能夠了,當須要保證線程安全時,可使用around advice。
使用@Around能夠聲明around advice,around advice的第一個參數必須是ProceedingJoinPoint類型的,在around advice中調用其proceed()方法會讓被代理方法開始執行。
如下示例演示如何使用around advice:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
public class AroundExample {
@Around("com.xyz.myapp.SystemArchitecture.businessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.proceed(); // stop stopwatch return retVal; }
}
Advice Parameters
Spring提供了對於advice中所需參數的支持,只須要在advice中定義相關的參數便可(好比以前的returing和throwing).
Access to the Current JoinPoint
每一種advice均可以聲明一個org.aspectj.lang.JoinPoint入參(around advice必須聲明)做爲第一個參數,JointPoint可提供以下方法:
getArgs(): Returns the method arguments.
getThis(): Returns the proxy object.
getTarget(): Returns the target object.
getSignature(): Returns a description of the method that is being advised.
toString(): Prints a useful description of the method being advised.
Passing Parameters to Advice
可使用args將參數傳遞給advice,如下例子中com.xyz.myapp.SystemArchitecture.dataAccessOperation使用account做爲方法的第一個入參:
@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
public void validateAccount(Account account) {
// ...
}
args(account,..) 實現了兩個功能:第一,當前advice僅匹配使用account做爲第一個參數的方法,第二,其將account參數傳遞給了advice。
另外一種方法時聲明一個提供account的接入點,而後接入點將account提供給advice
@Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
private void accountDataAccessOperation(Account account) {}
@Before("accountDataAccessOperation(account)")
public void validateAccount(Account account) {
// ...
}
proxy object(this),target object(target)和annotation ( @within, @target, @annotation, and @args) 可使用相似的方法獲取參數,如下例子展現如何
匹配@Auditable註解的方法並獲取@Auditable接口引用:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auditable {
AuditCode value();
}
@Before("com.xyz.lib.Pointcuts.anyPublicMethod() && @annotation(auditable)")
public void audit(Auditable auditable) {
AuditCode code = auditable.value();
// ...
}
Advice Parameters and Generics
Spring AOP能夠處理用在類聲明和方法入參中的範型,好比有一個以下的範型類:
public interface Sample
void sampleGenericMethod(T param);
void sampleGenericCollectionMethod(Collection
}
以下advice能夠對範型類中具體的方法生效:
@Before("execution(* ..Sample+.sampleGenericMethod(*)) && args(param)")
public void beforeSampleMethod(MyType param) {
// Advice implementation
}
以下advice對範型集合沒法生效:
@Before("execution(* ..Sample+.sampleGenericCollectionMethod(*)) && args(param)")
public void beforeSampleMethod(Collection
// Advice implementation
}
Determining Argument Names
The parameter binding in advice invocations relies on matching names used in pointcut expressions to declared parameter names in advice and pointcut method signatures. Parameter names are not available through Java reflection, so Spring AOP uses the following strategy to determine parameter names:
If the parameter names have been explicitly specified by the user, the specified parameter names are used. Both the advice and the pointcut annotations have an optional argNames attribute that you can use to specify the argument names of the annotated method. These argument names are available at runtime. The following example shows how to use the argNames attribute:
@Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
argNames="bean,auditable")
public void audit(Object bean, Auditable auditable) {
AuditCode code = auditable.value();
// ... use code and bean
}
If the first parameter is of the JoinPoint, ProceedingJoinPoint, or JoinPoint.StaticPart type, you ca leave out the name of the parameter from the value of the argNames attribute. For example, if you modify the preceding advice to receive the join point object, the argNames attribute need not include it:
@Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
argNames="bean,auditable")
public void audit(JoinPoint jp, Object bean, Auditable auditable) {
AuditCode code = auditable.value();
// ... use code, bean, and jp
}
The special treatment given to the first parameter of the JoinPoint, ProceedingJoinPoint, and JoinPoint.StaticPart types is particularly convenient for advice instances that do not collect any other join point context. In such situations, you may omit the argNames attribute. For example, the following advice need not declare the argNames attribute:
@Before("com.xyz.lib.Pointcuts.anyPublicMethod()")
public void audit(JoinPoint jp) {
// ... use jp
}
Using the 'argNames' attribute is a little clumsy, so if the 'argNames' attribute has not been specified, Spring AOP looks at the debug information for the class and tries to determine the parameter names from the local variable table. This information is present as long as the classes have been compiled with debug information ( '-g:vars' at a minimum). The consequences of compiling with this flag on are: (1) your code is slightly easier to understand (reverse engineer), (2) the class file sizes are very slightly bigger (typically inconsequential), (3) the optimization to remove unused local variables is not applied by your compiler. In other words, you should encounter no difficulties by building with this flag on.
If an @AspectJ aspect has been compiled by the AspectJ compiler (ajc) even without the debug information, you need not add the argNames attribute, as the compiler retain the needed information.
If the code has been compiled without the necessary debug information, Spring AOP tries to deduce the pairing of binding variables to parameters (for example, if only one variable is bound in the pointcut expression, and the advice method takes only one parameter, the pairing is obvious). If the binding of variables is ambiguous given the available information, an AmbiguousBindingException is thrown.
If all of the above strategies fail, an IllegalArgumentException is thrown.
Proceeding with Arguments
We remarked earlier that we would describe how to write a proceed call with arguments that works consistently across Spring AOP and AspectJ. The solution is to ensure that the advice signature binds each of the method parameters in order. The following example shows how to do so:
@Around("execution(List
"com.xyz.myapp.SystemArchitecture.inDataAccessLayer() && " +
"args(accountHolderNamePattern)")
public Object preProcessQueryPattern(ProceedingJoinPoint pjp,
String accountHolderNamePattern) throws Throwable {
String newPattern = preProcess(accountHolderNamePattern);
return pjp.proceed(new Object[] {newPattern});
}
In many cases, you do this binding anyway (as in the preceding example).
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 (so, given two pieces of after advice, the one with the highest precedence will run second).
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.
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.
4.Introductions
Introductions使aspect能夠聲明advice能夠實現一個給定的接口,而且提供該接口的實現。
可使用@DeclareParents註解來聲明一個Introduction,下例中,給定一個UsageTracked接口和DefaultUsageTracked的接口實現類,aspect聲明全部service接口的實現類一樣實現了UsageTracked接口:
@Aspect
public class UsageTracking {
@DeclareParents(value="com.xzy.myapp.service.*+", defaultImpl=DefaultUsageTracked.class) public static UsageTracked mixin; @Before("com.xyz.myapp.SystemArchitecture.businessService() && this(usageTracked)") public void recordUsage(UsageTracked usageTracked) { usageTracked.incrementUseCount(); }
}
5.Aspect Instantiation Models
This is an advanced topic. If you are just starting out with AOP, you can safely skip it until later.
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 pertypewithin are not currently supported).
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.
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.
6.An AOP Example
業務的執行可能會由於多線程問題而失敗(好比死鎖問題),若是須要進行重試,咱們但願在用戶無感知的狀況下進行重試操做,所以一個理想的選擇是使用aspect。
由於須要重試操做,所以使用around advice來屢次調用proceed:
@Aspect
public class ConcurrentOperationExecutor implements Ordered {
private static final int DEFAULT_MAX_RETRIES = 2; private int maxRetries = DEFAULT_MAX_RETRIES; private int order = 1; public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } @Around("com.xyz.myapp.SystemArchitecture.businessService()") public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { int numAttempts = 0; PessimisticLockingFailureException lockFailureException; do { numAttempts++; try { return pjp.proceed(); } catch(PessimisticLockingFailureException ex) { lockFailureException = ex; } } while(numAttempts <= this.maxRetries); throw lockFailureException; }
}
這個切面實現了Ordered接口並將其order設爲1(高於事務advice),這樣的話每次執行都會有一個純淨的事務。
對應的spring xml配置文件,建立對應的bean並設置maxRetries和order:
To refine the aspect so that it retries only idempotent operations, we might define the following Idempotent annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {
// marker annotation
}
We can then use the annotation to annotate the implementation of service operations. The change to the aspect to retry only idempotent operations involves refining the pointcut expression so that only @Idempotent operations match, as follows:
@Around("com.xyz.myapp.SystemArchitecture.businessService() && " +
"@annotation(com.xyz.myapp.service.Idempotent)")
public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
...
}
7.基於xml配置文件的aop配置
If you prefer an XML-based format, Spring also offers support for defining aspects using the new aop namespace tags. The exact same pointcut expressions and advice kinds as when using the @AspectJ style are supported. Hence, in this section we focus on the new syntax and refer the reader to the discussion in the previous section (@AspectJ support) for an understanding of writing pointcut expressions and the binding of advice parameters.
To use the aop namespace tags described in this section, you need to import the spring-aop schema, as described in XML Schema-based configuration. See the AOP schema for how to import the tags in the aop namespace.
Within your Spring configurations, all aspect and advisor elements must be placed within an < aop:config > element (you can have more than one < aop:config > element in an application context configuration). An < aop:config > element can contain pointcut, advisor, and aspect elements (note that these must be declared in that order).
The < aop:config > style of configuration makes heavy use of Spring’s auto-proxying mechanism. This can cause issues (such as advice not being woven) if you already use explicit auto-proxying through the use of BeanNameAutoProxyCreator or something similar. The recommended usage pattern is to use either only the < aop:config > style or only the AutoProxyCreator style and never mix them.
7.1. Declaring an Aspect
When you use the schema support, an aspect is a regular Java object defined as a bean in your Spring application context. The state and behavior are captured in the fields and methods of the object, and the pointcut and advice information are captured in the XML.
You can declare an aspect by using the
...
...
The bean that backs the aspect (aBean in this case) can of course be configured and dependency injected just like any other Spring bean.
7.2. Declaring a Pointcut
You can declare a named pointcut inside an
A pointcut that represents the execution of any business service in the service layer can be defined as follows:
<aop:pointcut id="businessService" expression="execution(* com.xyz.myapp.service.*.*(..))"/>
Note that the pointcut expression itself is using the same AspectJ pointcut expression language as described in @AspectJ support. If you use the schema based declaration style, you can refer to named pointcuts defined in types (@Aspects) within the pointcut expression. Another way of defining the above pointcut would be as follows:
<aop:pointcut id="businessService" expression="com.xyz.myapp.SystemArchitecture.businessService()"/>
Assume that you have a SystemArchitecture aspect as described in Sharing Common Pointcut Definitions.
Then declaring a pointcut inside an aspect is very similar to declaring a top-level pointcut, as the following example shows:
<aop:aspect id="myAspect" ref="aBean"> <aop:pointcut id="businessService" expression="execution(* com.xyz.myapp.service.*.*(..))"/> ... </aop:aspect>
In much the same way as an @AspectJ aspect, pointcuts declared by using the schema based definition style can collect join point context. For example, the following pointcut collects the this object as the join point context and passes it to the advice:
<aop:aspect id="myAspect" ref="aBean"> <aop:pointcut id="businessService" expression="execution(* com.xyz.myapp.service.*.*(..)) && this(service)"/> <aop:before pointcut-ref="businessService" method="monitor"/> ... </aop:aspect>
The advice must be declared to receive the collected join point context by including parameters of the matching names, as follows:
public void monitor(Object service) {
...
}
When combining pointcut sub-expressions, && is awkward within an XML document, so you can use the and, or, and not keywords in place of &&, ||, and !, respectively. For example, the previous pointcut can be better written as follows:
<aop:aspect id="myAspect" ref="aBean"> <aop:pointcut id="businessService" expression="execution(* com.xyz.myapp.service..(..)) and this(service)"/> <aop:before pointcut-ref="businessService" method="monitor"/> ... </aop:aspect>
Note that pointcuts defined in this way are referred to by their XML id and cannot be used as named pointcuts to form composite pointcuts. The named pointcut support in the schema-based definition style is thus more limited than that offered by the @AspectJ style.
7.3. Declaring Advice
The schema-based AOP support uses the same five kinds of advice as the @AspectJ style, and they have exactly the same semantics.
Before Advice
Before advice runs before a matched method execution. It is declared inside an
<aop:before pointcut-ref="dataAccessOperation" method="doAccessCheck"/> ...
Here, dataAccessOperation is the id of a pointcut defined at the top (
<aop:before pointcut="execution(* com.xyz.myapp.dao.*.*(..))" method="doAccessCheck"/> ...
As we noted in the discussion of the @AspectJ style, using named pointcuts can significantly improve the readability of your code.
The method attribute identifies a method (doAccessCheck) that provides the body of the advice. This method must be defined for the bean referenced by the aspect element that contains the advice. Before a data access operation is executed (a method execution join point matched by the pointcut expression), the doAccessCheck method on the aspect bean is invoked.
After Returning Advice
After returning advice runs when a matched method execution completes normally. It is declared inside an
<aop:after-returning pointcut-ref="dataAccessOperation" method="doAccessCheck"/> ...
As in the @AspectJ style, you can get the return value within the advice body. To do so, use the returning attribute to specify the name of the parameter to which the return value should be passed, as the following example shows:
<aop:after-returning pointcut-ref="dataAccessOperation" returning="retVal" method="doAccessCheck"/> ...
The doAccessCheck method must declare a parameter named retVal. The type of this parameter constrains matching in the same way as described for @AfterReturning. For example, you can decleare the method signature as follows:
public void doAccessCheck(Object retVal) {...
After Throwing Advice
After throwing advice executes when a matched method execution exits by throwing an exception. It is declared inside an
<aop:after-throwing pointcut-ref="dataAccessOperation" method="doRecoveryActions"/> ...
As in the @AspectJ style, you can get the thrown exception within the advice body. To do so, use the throwing attribute to specify the name of the parameter to which the exception should be passed as the following example shows:
<aop:after-throwing pointcut-ref="dataAccessOperation" throwing="dataAccessEx" method="doRecoveryActions"/> ...
The doRecoveryActions method must declare a parameter named dataAccessEx. The type of this parameter constrains matching in the same way as described for @AfterThrowing. For example, the method signature may be declared as follows:
public void doRecoveryActions(DataAccessException dataAccessEx) {...
After (Finally) Advice
After (finally) advice runs no matter how a matched method execution exits. You can declare it by using the after element, as the following example shows:
<aop:after pointcut-ref="dataAccessOperation" method="doReleaseLock"/> ...
Around Advice
The last kind of advice is around advice. Around advice runs 「around」 a matched method 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 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. Do not use around advice if before advice can do the job.
You can declare around advice by using the aop:around element. 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 may also be called with an Object[]. The values in the array are used as the arguments to the method execution when it proceeds. See Around Advice for notes on calling proceed with an Object[]. The following example shows how to declare around advice in XML:
<aop:around pointcut-ref="businessService" method="doBasicProfiling"/> ...
The implementation of the doBasicProfiling advice can be exactly the same as in the @AspectJ example (minus the annotation, of course), as the following example shows:
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
Advice Parameters
The schema-based declaration style supports fully typed advice in the same way as described for the @AspectJ support — by matching pointcut parameters by name against advice method parameters. See Advice Parameters for details. If you wish to explicitly specify argument names for the advice methods (not relying on the detection strategies previously described), you can do so by using the arg-names attribute of the advice element, which is treated in the same manner as the argNames attribute in an advice annotation (as described in Determining Argument Names). The following example shows how to specify an argument name in XML:
The arg-names attribute accepts a comma-delimited list of parameter names.
The following slightly more involved example of the XSD-based approach shows some around advice used in conjunction with a number of strongly typed parameters:
package x.y.service;
public interface PersonService {
Person getPerson(String personName, int age);
}
public class DefaultFooService implements FooService {
public Person getPerson(String name, int age) { return new Person(name, age); }
}
Next up is the aspect. Notice the fact that the profile(..) method accepts a number of strongly-typed parameters, the first of which happens to be the join point used to proceed with the method call. The presence of this parameter is an indication that the profile(..) is to be used as around advice, as the following example shows:
package x.y;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;
public class SimpleProfiler {
public Object profile(ProceedingJoinPoint call, String name, int age) throws Throwable { StopWatch clock = new StopWatch("Profiling for '" + name + "' and '" + age + "'"); try { clock.start(call.toShortString()); return call.proceed(); } finally { clock.stop(); System.out.println(clock.prettyPrint()); } }
}
Finally, the following example XML configuration effects the execution of the preceding advice for a particular join point:
<!-- this is the object that will be proxied by Spring's AOP infrastructure --> <bean id="personService" class="x.y.service.DefaultPersonService"/> <!-- this is the actual advice itself --> <bean id="profiler" class="x.y.SimpleProfiler"/> <aop:config> <aop:aspect ref="profiler"> <aop:pointcut id="theExecutionOfSomePersonServiceMethod" expression="execution(* x.y.service.PersonService.getPerson(String,int)) and args(name, age)"/> <aop:around pointcut-ref="theExecutionOfSomePersonServiceMethod" method="profile"/> </aop:aspect> </aop:config>
Consider the following driver script:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import x.y.service.PersonService;
public final class Boot {
public static void main(final String[] args) throws Exception { BeanFactory ctx = new ClassPathXmlApplicationContext("x/y/plain.xml"); PersonService person = (PersonService) ctx.getBean("personService"); person.getPerson("Pengo", 12); }
}
With such a Boot class, we would get output similar to the folloiwng on standard output:
00000 ? execution(getFoo)
Advice Ordering
When multiple advice needs to execute at the same join point (executing method) the ordering rules are as described in Advice Ordering. The precedence between aspects is determined by either adding the Order annotation to the bean that backs the aspect or by having the bean implement the Ordered interface.
7.4. Introductions
Introductions (known as inter-type declarations in AspectJ) let an aspect declare that advised objects implement a given interface and provide an implementation of that interface on behalf of those objects.
You can make an introduction by using the aop:declare-parents element inside an aop:aspect. You can use the aop:declare-parents element to declare that matching types have a new parent (hence the name). For example, given an interface named UsageTracked and an implementation of that interface named DefaultUsageTracked, the following aspect declares that all implementors of service interfaces also implement the UsageTracked interface. (In order to expose statistics through JMX for example.)
<aop:declare-parents types-matching="com.xzy.myapp.service.*+" implement-interface="com.xyz.myapp.service.tracking.UsageTracked" default-impl="com.xyz.myapp.service.tracking.DefaultUsageTracked"/> <aop:before pointcut="com.xyz.myapp.SystemArchitecture.businessService() and this(usageTracked)" method="recordUsage"/>
The class that backs the usageTracking bean would then contain the following method:
public void recordUsage(UsageTracked usageTracked) {
usageTracked.incrementUseCount();
}
The interface to be implemented is determined by the implement-interface attribute. The value of the types-matching attribute is an AspectJ type pattern. Any bean of a matching type implements the UsageTracked interface. Note that, in the before advice of the preceding example, service beans can be directly used as implementations of the UsageTracked interface. To access a bean programmatically, you could write the following:
UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
7.5. Aspect Instantiation Models
The only supported instantiation model for schema-defined aspects is the singleton model. Other instantiation models may be supported in future releases.
7.5.1. Advisors
The concept of 「advisors」 comes from the AOP support defined in Spring and does not have a direct equivalent in AspectJ. An advisor is like a small self-contained aspect that has a single piece of advice. The advice itself is represented by a bean and must implement one of the advice interfaces described in Advice Types in Spring. Advisors can take advantage of AspectJ pointcut expressions.
Spring supports the advisor concept with the
<aop:pointcut id="businessService" expression="execution(* com.xyz.myapp.service.*.*(..))"/> <aop:advisor pointcut-ref="businessService" advice-ref="tx-advice"/>
As well as the pointcut-ref attribute used in the preceding example, you can also use the pointcut attribute to define a pointcut expression inline.
To define the precedence of an advisor so that the advice can participate in ordering, use the order attribute to define the Ordered value of the advisor.
7.5.2. An AOP Schema Example
This section shows how the concurrent locking failure retry example from An AOP Example looks when rewritten with the schema support.
The execution of business services can sometimes fail due to concurrency issues (for example, a deadlock loser). If the operation is retried, it is likely to succeed on the next try. For business services where it is appropriate to retry in such conditions (idempotent operations that do not need to go back to the user for conflict resolution), we want to transparently retry the operation to avoid the client seeing a PessimisticLockingFailureException. This is a requirement that clearly cuts across multiple services in the service layer and, hence, is ideal for implementing through an aspect.
Because we want to retry the operation, we need to use around advice so that we can call proceed multiple times. The following listing shows the basic aspect implementation (which is a regular Java class that uses the schema support):
public class ConcurrentOperationExecutor implements Ordered {
private static final int DEFAULT_MAX_RETRIES = 2; private int maxRetries = DEFAULT_MAX_RETRIES; private int order = 1; public void setMaxRetries(int maxRetries) { this.maxRetries = maxRetries; } public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { int numAttempts = 0; PessimisticLockingFailureException lockFailureException; do { numAttempts++; try { return pjp.proceed(); } catch(PessimisticLockingFailureException ex) { lockFailureException = ex; } } while(numAttempts <= this.maxRetries); throw lockFailureException; }
}
Note that the aspect implements the Ordered interface so that we can set the precedence of the aspect higher than the transaction advice (we want a fresh transaction each time we retry). The maxRetries and order properties are both configured by Spring. The main action happens in the doConcurrentOperation around advice method. We try to proceed. If we fail with a PessimisticLockingFailureException, we try again, unless we have exhausted all of our retry attempts.
This class is identical to the one used in the @AspectJ example, but with the annotations removed.
The corresponding Spring configuration is as follows:
<aop:aspect id="concurrentOperationRetry" ref="concurrentOperationExecutor"> <aop:pointcut id="idempotentOperation" expression="execution(* com.xyz.myapp.service.*.*(..))"/> <aop:around pointcut-ref="idempotentOperation" method="doConcurrentOperation"/> </aop:aspect>
Notice that, for the time, being we assume that all business services are idempotent. If this is not the case, we can refine the aspect so that it retries only genuinely idempotent operations, by introducing an Idempotent annotation and using the annotation to annotate the implementation of service operations, as the following example shows:
@Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {
// marker annotation
}
The change to the aspect to retry only idempotent operations involves refining the pointcut expression so that only @Idempotent operations match, as follows:
7.6. Choosing which AOP Declaration Style to Use
選擇Spring AOP和仍是AspectJ以及使用Aspect語言,@AspectJ註解仍是Spring XML配置文件取決於系統要求,開發使用的IDE(Eclipse對於AspectJ的支持性更好)以及團隊對於AOP的熟悉程度。
7.6.1. Spring AOP or Full AspectJ?
Spring建議在Spring框架中使用Spring AOP,在其餘狀況下使用AspectJ。
7.6.2. @AspectJ or XML for Spring AOP?
If you have chosen to use Spring AOP, you have a choice of @AspectJ or XML style. There are various tradeoffs to consider.
The XML style may most familiar to existing Spring users, and it is backed by genuine POJOs. When using AOP as a tool to configure enterprise services, XML can be a good choice (a good test is whether you consider the pointcut expression to be a part of your configuration that you might want to change independently). With the XML style, it is arguably clearer from your configuration what aspects are present in the system.
The XML style has two disadvantages. First, it does not fully encapsulate the implementation of the requirement it addresses in a single place. The DRY principle says that there should be a single, unambiguous, authoritative representation of any piece of knowledge within a system. When using the XML style, the knowledge of how a requirement is implemented is split across the declaration of the backing bean class and the XML in the configuration file. When you use the @AspectJ style, this information is encapsulated in a single single module: the aspect. Secondly, the XML style is slightly more limited in what it can express than the @AspectJ style: Only the 「singleton」 aspect instantiation model is supported, and it is not possible to combine named pointcuts declared in XML. For example, in the @AspectJ style you can write something like the following:
@Pointcut("execution(* get*())")
public void propertyAccess() {}
@Pointcut("execution(org.xyz.Account+ *(..))")
public void operationReturningAnAccount() {}
@Pointcut("propertyAccess() && operationReturningAnAccount()")
public void accountPropertyAccess() {}
In the XML style you can declare the first two pointcuts:
The downside of the XML approach is that you cannot define the accountPropertyAccess pointcut by combining these definitions.
The @AspectJ style supports additional instantiation models and richer pointcut composition. It has the advantage of keeping the aspect as a modular unit. It also has the advantage that the @AspectJ aspects can be understood (and thus consumed) both by Spring AOP and by AspectJ. So, if you later decide you need the capabilities of AspectJ to implement additional requirements, you can easily migrate to an AspectJ-based approach. On balance, the Spring team prefers the @AspectJ style whenever you have aspects that do more than simple configuration of enterprise services.
7.7. Mixing Aspect Types
It is perfectly possible to mix @AspectJ style aspects by using the auto-proxying support, schema-defined
7.8. Proxying Mechanisms
Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. (JDK dynamic proxies are preferred whenever you have a choice).
If the target object to be proxied implements at least one interface, a JDK dynamic proxy is used. All of the interfaces implemented by the target type are proxied. If the target object does not implement any interfaces, a CGLIB proxy is created.
If you want to force the use of CGLIB proxying (for example, to proxy every method defined for the target object, not only those implemented by its interfaces), you can do so. However, you should consider the following issues:
final methods cannot be advised, as they cannot be overridden.
As of Spring 3.2, it is no longer necessary to add CGLIB to your project classpath, as CGLIB classes are repackaged under org.springframework and included directly in the spring-core JAR. This means that CGLIB-based proxy support 「just works」, in the same way that JDK dynamic proxies always have.
As of Spring 4.0, the constructor of your proxied object is NOT called twice any more, since the CGLIB proxy instance is created through Objenesis. Only if your JVM does not allow for constructor bypassing, you might see double invocations and corresponding debug log entries from Spring’s AOP support.
To force the use of CGLIB proxies, set the value of the proxy-target-class attribute of the
To force CGLIB proxying when you use the @AspectJ auto-proxy support, set the proxy-target-class attribute of the
Multiple
To be clear, using proxy-target-class="true" on
7.8.1. Understanding AOP Proxies
SpringAOP基於代理,當方法存在自我調用的狀況時(方法調用了自身類的方法this.xxx()),Spring AOP對於方法沒法生效(解決方法參考https://blog.csdn.net/zknxx/article/details/72585822)。
Consider first the scenario where you have a plain-vanilla, un-proxied, nothing-special-about-it, straight object reference, as the following code snippet shows:
public class SimplePojo implements Pojo {
public void foo() { // this next method invocation is a direct call on the 'this' reference this.bar(); } public void bar() { // some logic... }
}
If you invoke a method on an object reference, the method is invoked directly on that object reference, as the following image and listing show:
aop proxy plain pojo call
public class Main {
public static void main(String[] args) { Pojo pojo = new SimplePojo(); // this is a direct method call on the 'pojo' reference pojo.foo(); }
}
Things change slightly when the reference that client code has is a proxy. Consider the following diagram and code snippet:
aop proxy call
public class Main {
public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(new SimplePojo()); factory.addInterface(Pojo.class); factory.addAdvice(new RetryAdvice()); Pojo pojo = (Pojo) factory.getProxy(); // this is a method call on the proxy! pojo.foo(); }
}
The key thing to understand here is that the client code inside the main(..) method of the Main class has a reference to the proxy. This means that method calls on that object reference are calls on the proxy. As a result, the proxy can delegate to all of the interceptors (advice) that are relevant to that particular method call. However, once the call has finally reached the target object (the SimplePojo, reference in this case), any method calls that it may make on itself, such as this.bar() or this.foo(), are going to be invoked against the this reference, and not the proxy. This has important implications. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.
自我調用問題的解決方法
Okay, so what is to be done about this? The best approach (the term, 「best,」 is used loosely here) is to refactor your code such that the self-invocation does not happen. This does entail some work on your part, but it is the best, least-invasive approach. The next approach is absolutely horrendous, and we hesitate to point it out, precisely because it is so horrendous. You can (painful as it is to us) totally tie the logic within your class to Spring AOP, as the following example shows:
public class SimplePojo implements Pojo {
public void foo() { // this works, but... gah! ((Pojo) AopContext.currentProxy()).bar(); } public void bar() { // some logic... }
}
This totally couples your code to Spring AOP, and it makes the class itself aware of the fact that it is being used in an AOP context, which flies in the face of AOP. It also requires some additional configuration when the proxy is being created, as the following example shows:
public class Main {
public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(new SimplePojo()); factory.adddInterface(Pojo.class); factory.addAdvice(new RetryAdvice()); factory.setExposeProxy(true); Pojo pojo = (Pojo) factory.getProxy(); // this is a method call on the proxy! pojo.foo(); }
}
Finally, it must be noted that AspectJ does not have this self-invocation issue because it is not a proxy-based AOP framework.
57.9. Programmatic Creation of @AspectJ Proxies
In addition to declaring aspects in your configuration by using either
You can use the org.springframework.aop.aspectj.annotation.AspectJProxyFactory class to create a proxy for a target object that is advised by one or more @AspectJ aspects. The basic usage for this class is very simple, as the following example shows:
// create a factory that can generate a proxy for the given target object
AspectJProxyFactory factory = new AspectJProxyFactory(targetObject);
// add an aspect, the class must be an @AspectJ aspect
// you can call this as many times as you need with different aspects
factory.addAspect(SecurityManager.class);
// you can also add existing aspect instances, the type of the object supplied must be an @AspectJ aspect
factory.addAspect(usageTracker);
// now get the proxy object...
MyInterfaceType proxy = factory.getProxy();
See the javadoc for more information.
7.10. Using AspectJ with Spring Applications
Everything we have covered so far in this chapter is pure Spring AOP. In this section, we look at how you can use the AspectJ compiler or weaver instead of or in addition to Spring AOP if your needs go beyond the facilities offered by Spring AOP alone.
Spring ships with a small AspectJ aspect library, which is available stand-alone in your distribution as spring-aspects.jar. You need to add this to your classpath in order to use the aspects in it. Using AspectJ to Dependency Inject Domain Objects with Spring and Other Spring aspects for AspectJ discuss the content of this library and how you can use it. Configuring AspectJ Aspects by Using Spring IoC discusses how to dependency inject AspectJ aspects that are woven using the AspectJ compiler. Finally, Load-time Weaving with AspectJ in the Spring Framework provides an introduction to load-time weaving for Spring applications that use AspectJ.
7.10.1. Using AspectJ to Dependency Inject Domain Objects with Spring
The Spring container instantiates and configures beans defined in your application context. It is also possible to ask a bean factory to configure a pre-existing object, given the name of a bean definition that contains the configuration to be applied. spring-aspects.jar contains an annotation-driven aspect that exploits this capability to allow dependency injection of any object. The support is intended to be used for objects created outside of the control of any container. Domain objects often fall into this category because they are often created programmatically with the new operator or by an ORM tool as a result of a database query.
The @Configurable annotation marks a class as being eligible for Spring-driven configuration. In the simplest case, you can use purely it as a marker annotation, as the following example shows:
package com.xyz.myapp.domain;
import org.springframework.beans.factory.annotation.Configurable;
@Configurable
public class Account {
// ...
}
When used as a marker interface in this way, Spring configures new instances of the annotated type (Account, in this case) by using a bean definition (typically prototype-scoped) with the same name as the fully-qualified type name (com.xyz.myapp.domain.Account). Since the default name for a bean is the fully-qualified name of its type, a convenient way to declare the prototype definition is to omit the id attribute, as the following example shows:
If you want to explicitly specify the name of the prototype bean definition to use, you can do so directly in the annotation, as the following example shows:
package com.xyz.myapp.domain;
import org.springframework.beans.factory.annotation.Configurable;
@Configurable("account")
public class Account {
// ...
}
Spring now looks for a bean definition named account and uses that as the definition to configure new Account instances.
You can also use autowiring to avoid having to specify a dedicated bean definition at all. To have Spring apply autowiring, use the autowire property of the @Configurable annotation. You can specify either @Configurable(autowire=Autowire.BY_TYPE) or @Configurable(autowire=Autowire.BY_NAME for autowiring by type or by name, respectively. As an alternative, as of Spring 2.5, it is preferable to specify explicit, annotation-driven dependency injection for your @Configurable beans by using @Autowired or @Inject at the field or method level (see Annotation-based Container Configuration for further details).
Finally, you can enable Spring dependency checking for the object references in the newly created and configured object by using the dependencyCheck attribute (for example, @Configurable(autowire=Autowire.BY_NAME,dependencyCheck=true)). If this attribute is set to true, Spring validates after configuration that all properties (which are not primitives or collections) have been set.
Note that using the annotation on its own does nothing. It is the AnnotationBeanConfigurerAspect in spring-aspects.jar that acts on the presence of the annotation. In essence, the aspect says, 「after returning from the initialization of a new object of a type annotated with @Configurable, configure the newly created object using Spring in accordance with the properties of the annotation」. In this context, 「initialization」 refers to newly instantiated objects (for example, objects instantiated with the new operator) as well as to Serializable objects that are undergoing deserialization (for example, through readResolve()).
One of the key phrases in the above paragraph is 「in essence」. For most cases, the exact semantics of 「after returning from the initialization of a new object」 are fine. In this context, 「after initialization」 means that the dependencies are injected after the object has been constructed. This means that the dependencies are not available for use in the constructor bodies of the class. If you want the dependencies to be injected before the constructor bodies execute and thus be available for use in the body of the constructors, you need to define this on the @Configurable declaration, as follows:
@Configurable(preConstruction=true)
You can find more information about the language semantics of the various pointcut types in AspectJ in this appendix of the AspectJ Programming Guide.
For this to work, the annotated types must be woven with the AspectJ weaver. You can either use a build-time Ant or Maven task to do this (see, for example, the AspectJ Development Environment Guide) or load-time weaving (see Load-time Weaving with AspectJ in the Spring Framework). The AnnotationBeanConfigurerAspect itself needs to be configured by Spring (in order to obtain a reference to the bean factory that is to be used to configure new objects). If you use Java-based configuration, you can add @EnableSpringConfigured to any @Configuration class, as follows:
@Configuration
@EnableSpringConfigured
public class AppConfig {
}
If you prefer XML based configuration, the Spring context namespace defines a convenient context:spring-configured element, which you can use as follows:
Instances of @Configurable objects created before the aspect has been configured result in a message being issued to the debug log and no configuration of the object taking place. An example might be a bean in the Spring configuration that creates domain objects when it is initialized by Spring. In this case, you can use the depends-on bean attribute to manually specify that the bean depends on the configuration aspect. The following example shows how to use the depends-on attribute:
<!-- ... -->
Do not activate @Configurable processing through the bean configurer aspect unless you really mean to rely on its semantics at runtime. In particular, make sure that you do not use @Configurable on bean classes that are registered as regular Spring beans with the container. Doing so results in double initialization, once through the container and once through the aspect.
Unit Testing @Configurable Objects
One of the goals of the @Configurable support is to enable independent unit testing of domain objects without the difficulties associated with hard-coded lookups. If @Configurable types have not been woven by AspectJ, the annotation has no affect during unit testing. You can set mock or stub property references in the object under test and proceed as normal. If @Configurable types have been woven by AspectJ, you can still unit test outside of the container as normal, but you see a warning message each time that you construct an @Configurable object indicating that it has not been configured by Spring.
Working with Multiple Application Contexts
The AnnotationBeanConfigurerAspect that is used to implement the @Configurable support is an AspectJ singleton aspect. The scope of a singleton aspect is the same as the scope of static members: There is one aspect instance per classloader that defines the type. This means that, if you define multiple application contexts within the same classloader hierarchy, you need to consider where to define the @EnableSpringConfigured bean and where to place spring-aspects.jar on the classpath.
Consider a typical Spring web application configuration that has a shared parent application context that defines common business services, everything needed to support those services, and one child application context for each servlet (which contains definitions particular to that servlet). All of these contexts co-exist within the same classloader hierarchy, and so the AnnotationBeanConfigurerAspect can hold a reference to only one of them. In this case, we recommend defining the @EnableSpringConfigured bean in the shared (parent) application context. This defines the services that you are likely to want to inject into domain objects. A consequence is that you cannot configure domain objects with references to beans defined in the child (servlet-specific) contexts by using the @Configurable mechanism (which is probably not something you want to do anyway).
When deploying multiple web applications within the same container, ensure that each web application loads the types in spring-aspects.jar by using its own classloader (for example, by placing spring-aspects.jar in 'WEB-INF/lib'). If spring-aspects.jar is added only to the container-wide classpath (and hence loaded by the shared parent classloader), all web applications share the same aspect instance (which is probably not what you want).
7.10.2. Other Spring aspects for AspectJ
In addition to the @Configurable aspect, spring-aspects.jar contains an AspectJ aspect that you can use to drive Spring’s transaction management for types and methods annotated with the @Transactional annotation. This is primarily intended for users who want to use the Spring Framework’s transaction support outside of the Spring container.
The aspect that interprets @Transactional annotations is the AnnotationTransactionAspect. When you use this aspect, you must annotate the implementation class (or methods within that class or both), not the interface (if any) that the class implements. AspectJ follows Java’s rule that annotations on interfaces are not inherited.
A @Transactional annotation on a class specifies the default transaction semantics for the execution of any public operation in the class.
A @Transactional annotation on a method within the class overrides the default transaction semantics given by the class annotation (if present). Methods of any visibility may be annotated, including private methods. Annotating non-public methods directly is the only way to get transaction demarcation for the execution of such methods.
Since Spring Framework 4.2, spring-aspects provides a similar aspect that offers the exact same features for the standard javax.transaction.Transactional annotation. Check JtaAnnotationTransactionAspect for more details.
For AspectJ programmers who want to use the Spring configuration and transaction management support but do not want to (or cannot) use annotations, spring-aspects.jar also contains abstract aspects you can extend to provide your own pointcut definitions. See the sources for the AbstractBeanConfigurerAspect and AbstractTransactionAspect aspects for more information. As an example, the following excerpt shows how you could write an aspect to configure all instances of objects defined in the domain model by using prototype bean definitions that match the fully qualified class names:
public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect {
public DomainObjectConfiguration() { setBeanWiringInfoResolver(new ClassNameBeanWiringInfoResolver()); } // the creation of a new bean (any object in the domain model) protected pointcut beanCreation(Object beanInstance) : initialization(new(..)) && SystemArchitecture.inDomainModel() && this(beanInstance);
}
7.10.3. Configuring AspectJ Aspects by Using Spring IoC
When you use AspectJ aspects with Spring applications, it is natural to both want and expect to be able to configure such aspects with Spring. The AspectJ runtime itself is responsible for aspect creation, and the means of configuring the AspectJ-created aspects through Spring depends on the AspectJ instantiation model (the per-xxx clause) used by the aspect.
The majority of AspectJ aspects are singleton aspects. Configuration of these aspects is easy. You can create a bean definition that references the aspect type as normal and include the factory-method="aspectOf" bean attribute. This ensures that Spring obtains the aspect instance by asking AspectJ for it rather than trying to create an instance itself. The following example shows how to use the factory-method="aspectOf" attribute:
<property name="profilingStrategy" ref="jamonProfilingStrategy"/>
Note the factory-method="aspectOf" attribute
Non-singleton aspects are harder to configure. However, it is possible to do so by creating prototype bean definitions and using the @Configurable support from spring-aspects.jar to configure the aspect instances once they have bean created by the AspectJ runtime.
If you have some @AspectJ aspects that you want to weave with AspectJ (for example, using load-time weaving for domain model types) and other @AspectJ aspects that you want to use with Spring AOP, and these aspects are all configured in Spring, you need to tell the Spring AOP @AspectJ auto-proxying support which exact subset of the @AspectJ aspects defined in the configuration should be used for auto-proxying. You can do this by using one or more
Do not be misled by the name of the
7.10.4. Load-time Weaving with AspectJ in the Spring Framework
Load-time weaving (LTW) refers to the process of weaving AspectJ aspects into an application’s class files as they are being loaded into the Java virtual machine (JVM). The focus of this section is on configuring and using LTW in the specific context of the Spring Framework. This section is not a general introduction to LTW. For full details on the specifics of LTW and configuring LTW with only AspectJ (with Spring not being involved at all), see the LTW section of the AspectJ Development Environment Guide.
The value that the Spring Framework brings to AspectJ LTW is in enabling much finer-grained control over the weaving process. 'Vanilla' AspectJ LTW is effected by using a Java (5+) agent, which is switched on by specifying a VM argument when starting up a JVM. It is, thus, a JVM-wide setting, which may be fine in some situations but is often a little too coarse. Spring-enabled LTW lets you switch on LTW on a per-ClassLoader basis, which is more fine-grained and which can make more sense in a 'single-JVM-multiple-application' environment (such as is found in a typical application server environment).
Further, in certain environments, this support enables load-time weaving without making any modifications to the application server’s launch script that is needed to add -javaagent:path/to/aspectjweaver.jar or (as we describe later in this section) -javaagent:path/to/org.springframework.instrument-{version}.jar (previously named spring-agent.jar). Developers modify one or more files that form the application context to enable load-time weaving instead of relying on administrators who typically are in charge of the deployment configuration, such as the launch script.
Now that the sales pitch is over, let us first walk through a quick example of AspectJ LTW that uses Spring, followed by detailed specifics about elements introduced in the example. For a complete example, see the Petclinic sample application.
A First Example
Assume that you are an application developer who has been tasked with diagnosing the cause of some performance problems in a system. Rather than break out a profiling tool, we are going to switch on a simple profiling aspect that lets us quickly get some performance metrics. We can then apply a finer-grained profiling tool to that specific area immediately afterwards.
The example presented here uses XML configuration. You can also configure and use @AspectJ with Java configuration. Specifically, you can use the @EnableLoadTimeWeaving annotation as an alternative to
The following example shows the profiling aspect, which is not fancy — it is a time-based profiler that uses the @AspectJ-style of aspect declaration:
package foo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.util.StopWatch;
import org.springframework.core.annotation.Order;
@Aspect
public class ProfilingAspect {
@Around("methodsToBeProfiled()") public Object profile(ProceedingJoinPoint pjp) throws Throwable { StopWatch sw = new StopWatch(getClass().getSimpleName()); try { sw.start(pjp.getSignature().getName()); return pjp.proceed(); } finally { sw.stop(); System.out.println(sw.prettyPrint()); } } @Pointcut("execution(public * foo..*.*(..))") public void methodsToBeProfiled(){}
}
We also need to create an META-INF/aop.xml file, to inform the AspectJ weaver that we want to weave our ProfilingAspect into our classes. This file convention, namely the presence of a file (or files) on the Java classpath called META-INF/aop.xml is standard AspectJ. The following example shows the aop.xml file:
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<weaver> <!-- only weave classes in our application-specific packages --> <include within="foo.*"/> </weaver> <aspects> <!-- weave in just this aspect --> <aspect name="foo.ProfilingAspect"/> </aspects>
Now we can move on to the Spring-specific portion of the configuration. We need to configure a LoadTimeWeaver (explained later). This load-time weaver is the essential component responsible for weaving the aspect configuration in one or more META-INF/aop.xml files into the classes in your application. The good thing is that it does not require a lot of configuration (there are some more options that you can specify, but these are detailed later), as can be seen in the following example:
<!-- a service object; we will be profiling its methods --> <bean id="entitlementCalculationService" class="foo.StubEntitlementCalculationService"/> <!-- this switches on the load-time weaving --> <context:load-time-weaver/>
Now that all the required artifacts (the aspect, the META-INF/aop.xml file, and the Spring configuration) are in place, we can create the following driver class with a main(..) method to demonstrate the LTW in action:
package foo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class Main {
public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml", Main.class); EntitlementCalculationService entitlementCalculationService = (EntitlementCalculationService) ctx.getBean("entitlementCalculationService"); // the profiling aspect is 'woven' around this method execution entitlementCalculationService.calculateEntitlement(); }
}
We have one last thing to do. The introduction to this section did say that one could switch on LTW selectively on a per-ClassLoader basis with Spring, and this is true. However, for this example, we use a Java agent (supplied with Spring) to switch on the LTW. We use the folloiwng command to run the Main class shown earlier:
java -javaagent:C:/projects/foo/lib/global/spring-instrument.jar foo.Main
The -javaagent is a flag for specifying and enabling agents to instrument programs that run on the JVM. The Spring Framework ships with such an agent, the InstrumentationSavingAgent, which is packaged in the spring-instrument.jar that was supplied as the value of the -javaagent argument in the preceding example.
The output from the execution of the Main program looks something like the next example. (I have introduced a Thread.sleep(..) statement into the calculateEntitlement() implementation so that the profiler actually captures something other than 0 milliseconds (the 01234 milliseconds is not an overhead introduced by the AOP). The following listing shows the output we got when we ran our profiler:
Calculating entitlement
StopWatch 'ProfilingAspect': running time (millis) = 1234
------ ----- ----------------------------
ms % Task name
------ ----- ----------------------------
01234 100% calculateEntitlement
Since this LTW is effected by using full-blown AspectJ, we are not limited only to advising Spring beans. The following slight variation on the Main program yields the same result:
package foo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class Main {
public static void main(String[] args) { new ClassPathXmlApplicationContext("beans.xml", Main.class); EntitlementCalculationService entitlementCalculationService = new StubEntitlementCalculationService(); // the profiling aspect will be 'woven' around this method execution entitlementCalculationService.calculateEntitlement(); }
}
Notice how, in the preceding program, we bootstrap the Spring container and then create a new instance of the StubEntitlementCalculationService totally outside the context of Spring. The profiling advice still gets woven in.
Admittedly, the example is simplistic. However, the basics of the LTW support in Spring have all been introduced in the earlier example, and the rest of this section explains the 「why」 behind each bit of configuration and usage in detail.
The ProfilingAspect used in this example may be basic, but it is quite useful. It is a nice example of a development-time aspect that developers can use during development and then easily exclude from builds of the application being deployed into UAT or production.
Aspects
The aspects that you use in LTW have to be AspectJ aspects. You can write them in either the AspectJ language itself, or you can write your aspects in the @AspectJ-style. Your aspects are then both valid AspectJ and Spring AOP aspects. Furthermore, the compiled aspect classes need to be available on the classpath.
'META-INF/aop.xml'
The AspectJ LTW infrastructure is configured by using one or more META-INF/aop.xml files that are on the Java classpath (either directly or, more typically, in jar files).
The structure and contents of this file is detailed in the LTW part AspectJ reference documentation. Because the aop.xml file is 100% AspectJ, we do not describe it further here.
Required libraries (JARS)
At minimum, you need the following libraries to use the Spring Framework’s support for AspectJ LTW:
spring-aop.jar (version 2.5 or later, plus all mandatory dependencies)
aspectjweaver.jar (version 1.6.8 or later)
If you use the Spring-provided agent to enable instrumentation, you also need:
spring-instrument.jar
Spring Configuration
The key component in Spring’s LTW support is the LoadTimeWeaver interface (in the org.springframework.instrument.classloading package), and the numerous implementations of it that ship with the Spring distribution. A LoadTimeWeaver is responsible for adding one or more java.lang.instrument.ClassFileTransformers to a ClassLoader at runtime, which opens the door to all manner of interesting applications, one of which happens to be the LTW of aspects.
If you are unfamiliar with the idea of runtime class file transformation, see the javadoc API documentation for the java.lang.instrument package before continuing. While that documentation is not comprehensive, at least you can see the key interfaces and classes (for reference as you read through this section).
Configuring a LoadTimeWeaver for a particular ApplicationContext can be as easy as adding one line. (Note that you almost certainly need to use an ApplicationContext as your Spring container — typically, a BeanFactory is not enough because the LTW support uses BeanFactoryPostProcessors.)
To enable the Spring Framework’s LTW support, you need to configure a LoadTimeWeaver, which typically is done by using the @EnableLoadTimeWeaving annotation, as follows:
@Configuration
@EnableLoadTimeWeaving
public class AppConfig {
}
Alternatively, if you prefer XML-based configuration, use the
<context:load-time-weaver/>
The preceding configuration automatically defines and registers a number of LTW-specific infrastructure beans, such as a LoadTimeWeaver and an AspectJWeavingEnabler, for you. The default LoadTimeWeaver is the DefaultContextLoadTimeWeaver class, which attempts to decorate an automatically detected LoadTimeWeaver. The exact type of LoadTimeWeaver that is 「automatically detected」 is dependent upon your runtime environment. The following table summarizes various LoadTimeWeaver implementations:
Table 13. DefaultContextLoadTimeWeaver LoadTimeWeavers
Runtime Environment LoadTimeWeaver implementation
Running in Oracle’s WebLogic
WebLogicLoadTimeWeaver
Running in Oracle’s GlassFish
GlassFishLoadTimeWeaver
Running in Apache Tomcat
TomcatLoadTimeWeaver
Running in Red Hat’s JBoss AS or WildFly
JBossLoadTimeWeaver
Running in IBM’s WebSphere
WebSphereLoadTimeWeaver
JVM started with Spring InstrumentationSavingAgent (java -javaagent:path/to/spring-instrument.jar)
InstrumentationLoadTimeWeaver
Fallback, expecting the underlying ClassLoader to follow common conventions (for example applicable to TomcatInstrumentableClassLoader and Resin)
ReflectiveLoadTimeWeaver
Note that the table lists only the LoadTimeWeavers that are autodetected when you use the DefaultContextLoadTimeWeaver. You can specify exactly which LoadTimeWeaver implementation to use.
To specify a specific LoadTimeWeaver with Java configuration, implement the LoadTimeWeavingConfigurer interface and override the getLoadTimeWeaver() method. The following example specifies a ReflectiveLoadTimeWeaver:
@Configuration
@EnableLoadTimeWeaving
public class AppConfig implements LoadTimeWeavingConfigurer {
@Override public LoadTimeWeaver getLoadTimeWeaver() { return new ReflectiveLoadTimeWeaver(); }
}
If you use XML-based configuration, you can specify the fully qualified classname as the value of the weaver-class attribute on the
<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>
The LoadTimeWeaver that is defined and registered by the configuration can be later retrieved from the Spring container by using the well known name, loadTimeWeaver. Remember that the LoadTimeWeaver exists only as a mechanism for Spring’s LTW infrastructure to add one or more ClassFileTransformers. The actual ClassFileTransformer that does the LTW is the ClassPreProcessorAgentAdapter (from the org.aspectj.weaver.loadtime package) class. See the class-level javadoc of the ClassPreProcessorAgentAdapter class for further details, because the specifics of how the weaving is actually effected is beyond the scope of this document.
There is one final attribute of the configuration left to discuss: the aspectjWeaving attribute (or aspectj-weaving if you use XML). This attribute controls whether LTW is enabled or not. It accepts one of three possible values, with the default value being autodetect if the attribute is not present. The following table summarizes the three possible values:
Table 14. AspectJ weaving attribute values
Annotation Value XML Value Explanation
ENABLED
on
AspectJ weaving is on, and aspects are woven at load-time as appropriate.
DISABLED
off
LTW is off. No aspect is woven at load-time.
AUTODETECT
autodetect
If the Spring LTW infrastructure can find at least one META-INF/aop.xml file, then AspectJ weaving is on. Otherwise, it is off. This is the default value.
Environment-specific Configuration
This last section contains any additional settings and configuration that you need when you use Spring’s LTW support in environments such as application servers and web containers.
Tomcat
Historically, Apache Tomcat's default class loader did not support class transformation, which is why Spring provides an enhanced implementation that addresses this need. Named TomcatInstrumentableClassLoader, the loader works on Tomcat 6.0 and above.
Do not define TomcatInstrumentableClassLoader on Tomcat 8.0 and higher. Instead, let Spring automatically use Tomcat’s new native InstrumentableClassLoader facility through the TomcatLoadTimeWeaver strategy.
If you still need to use TomcatInstrumentableClassLoader, you can register it individually for each web application as follows:
Copy org.springframework.instrument.tomcat.jar into $CATALINA_HOME/lib, where $CATALINA_HOME represents the root of the Tomcat installation
Instruct Tomcat to use the custom class loader (instead of the default) by editing the web application context file, as the following example shows:
Apache Tomcat 6.0+ supports several context locations:
Server configuration file: $CATALINA_HOME/conf/server.xml
Default context configuration: $CATALINA_HOME/conf/context.xml, which affects all deployed web applications
A per-web application configuration, which can be deployed either on the server-side at $CATALINA_HOME/conf/[enginename]/[hostname]/[webapp]-context.xml or embedded inside the web-app archive at META-INF/context.xml
For efficiency, we recommend the embedded per-web application configuration style, because it impacts only applications that use the custom class loader and does not require any changes to the server configuration. See the Tomcat 6.0.x documentation for more details about available context locations.
Alternatively, consider using the Spring-provided generic VM agent, to be specified in Tomcat’s launch script (described earlier in this section). This makes instrumentation available to all deployed web applications, no matter the ClassLoader on which they happen to run.
WebLogic, WebSphere, Resin, GlassFish, and JBoss
Recent versions of WebLogic Server (version 10 and above), IBM WebSphere Application Server (version 7 and above), Resin (version 3.1 and above), and JBoss (version 6.x or above) provide a ClassLoader that is capable of local instrumentation. Spring’s native LTW leverages such ClassLoader implementations to enable AspectJ weaving. You can enable LTW by activating load-time weaving, as described earlier. Specifically, you do not need to modify the launch script to add -javaagent:path/to/spring-instrument.jar.
Note that the GlassFish instrumentation-capable ClassLoader is available only in its EAR environment. For GlassFish web applications, follow the Tomcat setup instructions outlined earlier.
Note that, on JBoss 6.x, you need to disable the app server scanning to prevent it from loading the classes before the application actually starts. A quick workaround is to add to your artifact a file named WEB-INF/jboss-scanning.xml with the following content:
Generic Java Applications
When class instrumentation is required in environments that do not support or are not supported by the existing LoadTimeWeaver implementations, a JDK agent can be the only solution. For such cases, Spring provides InstrumentationLoadTimeWeaver, which requires a Spring-specific (but very general) VM agent, org.springframework.instrument-{version}.jar (previously named spring-agent.jar).
To use it, you must start the virtual machine with the Spring agent by supplying the following JVM options:
-javaagent:/path/to/org.springframework.instrument-{version}.jar
Note that this requires modification of the VM launch script, which may prevent you from using this in application server environments (depending on your operation policies). Additionally, the JDK agent instruments the entire VM, which can be expensive.
For performance reasons, we recommend that you use this configuration only if your target environment (such as Jetty) does not have (or does not support) a dedicated LTW.
5.11. Further Resources
More information on AspectJ can be found on the AspectJ website.
Eclipse AspectJ by Adrian Colyer et. al. (Addison-Wesley, 2005) provides a comprehensive introduction and reference for the AspectJ language.
AspectJ in Action, Second Edition by Ramnivas Laddad (Manning, 2009) comes highly recommended. The focus of the book is on AspectJ, but a lot of general AOP themes are explored (in some depth).
8.1. Pointcut API in Spring
Spring pointcuts中的重要概念。
8.1.1. Concepts
Spring pointcut支持複用不一樣類型的advice,能夠爲同一個pointcut匹配不一樣的pointcut。
org.springframework.aop.Pointcut是pointcut的核心接口:
public interface Pointcut {
ClassFilter getClassFilter(); MethodMatcher getMethodMatcher();
}
將Pointcut分割爲兩個接口可使其支持類的複用以及和其餘Pointcut的聯合(union)。
ClassFilter接口用於將pointcut匹配到目標類:
public interface ClassFilter {
boolean matches(Class clazz);
}
MethodMatcher接口包括三個方法:matches(Method m, Class targetClass)用於測試PonitCut是否匹配到目標方法,isRunTime()返回true的話則調用matches(Method m, Class targetClass, Object[] args)方法,能夠獲取目標方法的入參:
public interface MethodMatcher {
boolean matches(Method m, Class targetClass); boolean isRuntime(); boolean matches(Method m, Class targetClass, Object[] args);
}
Most MethodMatcher implementations are static, meaning that their isRuntime() method returns false. In this case, the three-argument matches method is never invoked.
If possible, try to make pointcuts static, allowing the AOP framework to cache the results of pointcut evaluation when an AOP proxy is created.
8.1.2. Operations on Pointcuts
Spring supports operations (notably, union and intersection) on pointcuts.
Union means the methods that either pointcut matches. Intersection means the methods that both pointcuts match. Union is usually more useful. You can compose pointcuts by using the static methods in the org.springframework.aop.support.Pointcuts class or by using the ComposablePointcut class in the same package. However, using AspectJ pointcut expressions is usually a simpler approach.
8.1.3. AspectJ Expression Pointcuts
Since 2.0, the most important type of pointcut used by Spring is org.springframework.aop.aspectj.AspectJExpressionPointcut. This is a pointcut that uses an AspectJ-supplied library to parse an AspectJ pointcut expression string.
See the previous chapter for a discussion of supported AspectJ pointcut primitives.
8.1.4. Convenience Pointcut Implementations
Spring提供了幾種方便的pointcut接口的實現,用戶能夠直接使用它們。
Static Pointcuts
靜態Pointcuts基於目標類和方法,不能獲取被代理方法的入參(isRunTime()永遠返回false)。
Spring提供了幾種靜態Pointcuts的實現供用戶使用。
Regular Expression Pointcuts
One obvious way to specify static pointcuts is regular expressions. Several AOP frameworks besides Spring make this possible. org.springframework.aop.support.JdkRegexpMethodPointcut is a generic regular expression pointcut that uses the regular expression support in the JDK.
With the JdkRegexpMethodPointcut class, you can provide a list of pattern strings. If any of these is a match, the pointcut evaluates to true. (So, the result is effectively the union of these pointcuts.)
The following example shows how to use JdkRegexpMethodPointcut:
Spring provides a convenience class named RegexpMethodPointcutAdvisor, which lets us also reference an Advice (remember that an Advice can be an interceptor, before advice, throws advice, and others). Behind the scenes, Spring uses a JdkRegexpMethodPointcut. Using RegexpMethodPointcutAdvisor simplifies wiring, as the one bean encapsulates both pointcut and advice, as the following example shows:
You can use RegexpMethodPointcutAdvisor with any Advice type.
Attribute-driven Pointcuts
An important type of static pointcut is a metadata-driven pointcut. This uses the values of metadata attributes (typically, source-level metadata).
Dynamic pointcuts
Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account method arguments as well as static information. This means that they must be evaluated with every method invocation and that the result cannot be cached, as arguments will vary.
The main example is the control flow pointcut.
Control Flow Pointcuts
Spring control flow pointcuts are conceptually similar to AspectJ cflow pointcuts, although less powerful. (There is currently no way to specify that a pointcut executes below a join point matched by another pointcut.) A control flow pointcut matches the current call stack. For example, it might fire if the join point was invoked by a method in the com.mycompany.web package or by the SomeCaller class. Control flow pointcuts are specified by using the org.springframework.aop.support.ControlFlowPointcut class.
Control flow pointcuts are significantly more expensive to evaluate at runtime than even other dynamic pointcuts. In Java 1.4, the cost is about five times that of other dynamic pointcuts.
8.1.5. Pointcut Superclasses
Spring提供了幾種Pointcut的超類供用戶繼承使用,通常建議繼承StaticMethodMatcherPointcut來實現用戶本身的靜態Pointcut:
class TestStaticPointcut extends StaticMethodMatcherPointcut {
public boolean matches(Method m, Class targetClass) { // return true if custom criteria match }
}
8.1.6. Custom Pointcuts
Because pointcuts in Spring AOP are Java classes rather than language features (as in AspectJ), you can declare custom pointcuts, whether static or dynamic. Custom pointcuts in Spring can be arbitrarily complex. However, we recommend using the AspectJ pointcut expression language, if you can.
Later versions of Spring may offer support for 「semantic pointcuts」 as offered by JAC — for example, 「all methods that change instance variables in the target object.」
8.2. Advice API in Spring
Spring提供了Advice的API供用戶調用。
8.2.1. Advice Lifecycles
每一個advice都是Spring bean,一個advice實例能夠被全部advice對象共享或者僅被單個advice對象持有(advice分爲per-class和per-instance兩種).
Per-class advice使用的比較多,通常的advice好比事務使用的是per-class advice,不須要依賴被代理對象的狀態時可使用per-class advice,其僅能做用於方法和參數。
Per-instance advice is appropriate for introductions, to support mixins. In this case, the advice adds state to the proxied object.
8.2.2. Advice Types in Spring
Spring提供了幾種可拓展的advice供用戶使用。
Interception Around Advice
實現了around advice接口的類必須實現MethodInterceptor接口:
public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation invocation) throws Throwable;
}
MethodInvocation參數包括目標 join point,AOP 代理對象以及代理方法的參數,invoke()方法必須返回被代理方法的返回值。如下是MethodInterceptor接口的一個實現示例:
public class DebugInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("Before: invocation=[" + invocation + "]"); Object rval = invocation.proceed(); System.out.println("Invocation returned"); return rval; }
}
proceed()使攔截器鏈繼續向前執行,MethodInterceptor能夠返回一個不一樣的值或者拋出異常(可是通常不建議這麼作)。
MethodInterceptor implementations offer interoperability with other AOP Alliance-compliant AOP implementations. The other advice types discussed in the remainder of this section implement common AOP concepts but in a Spring-specific way. While there is an advantage in using the most specific advice type, stick with MethodInterceptor around advice if you are likely to want to run the aspect in another AOP framework. Note that pointcuts are not currently interoperable between frameworks, and the AOP Alliance does not currently define pointcut interfaces.
Before Advice
Before Advice不須要調用proceed()(只有around advice須要調用)來使攔截器鏈繼續執行,所以不會由於錯誤的調用process()致使攔截器鏈沒法繼續執行。
MethodBeforeAdvice接口:
public interface MethodBeforeAdvice extends BeforeAdvice {
void before(Method m, Object[] args, Object target) throws Throwable;
}
Before Advice能夠在鏈接點執行前執行操做,可是不能修改被代理方法的返回值。若是一個Before Advice拋出異常,那麼接下來的攔截器鏈將不會繼續執行。
以下的示例演示了一個統計方法調用次數的before advice:
public class CountingBeforeAdvice implements MethodBeforeAdvice {
private int count; public void before(Method m, Object[] args, Object target) throws Throwable { ++count; } public int getCount() { return count; }
}
Throws Advice
Throws Advice在joint point方法拋出異常後執行,通常實現org.springframework.aop.ThrowsAdvice,該接口只是一個標記接口,代表實現類是一個Throws Advice,
可是實現類應該實現一個以下方法:
afterThrowing([Method, args, target], subclassOfThrowable)
只有最後一個subclass Of Throwable參數是必需的,該方法能夠有一個或者四個入參,取決於advice是否想要處理被代理的方法和參數。如下是兩個示例:
如下advice在拋出一個RemoteException後被調用:
public class RemoteThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(RemoteException ex) throws Throwable { // Do something with remote exception }
}
如下示例定義了四個參數:被調用的方法(invoke method),方法參數(method arguments),target object(被代理類)以及對應的異常:
public class ServletThrowsAdviceWithArguments implements ThrowsAdvice {
public void afterThrowing(Method m, Object[] args, Object target, ServletException ex) { // Do something with all arguments }
}
如下示例說明上面兩種方法在同一個類中使用(用於處理兩種Exception),同一個Throws Advice能夠處理多種Exception:
public static class CombinedThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(RemoteException ex) throws Throwable { // Do something with remote exception } public void afterThrowing(Method m, Object[] args, Object target, ServletException ex) { // Do something with all arguments }
}
若是一個Throws Advice本身出現異常,那麼它會拋出一個異常覆蓋原有的異常(通常是一個RunTimeException),However, if a throws-advice method throws a checked exception, it must match the declared exceptions of the target method and is, hence, to some degree coupled to specific target method signatures. Do not throw an undeclared checked exception that is incompatible with the target method’s signature!
After Returning Advice
一個Spring中的after returning advice必須實現org.springframework.aop.AfterReturningAdvice接口,其定義以下:
public interface AfterReturningAdvice extends Advice {
void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable;
}
一個after returning advice能夠接觸到被代理方法的返回值(但不是不能修改),被代理方法,方法入參以及被代理類。
如下after returning advice統計了全部正常運行的方法調用次數:
public class CountingAfterReturningAdvice implements AfterReturningAdvice {
private int count; public void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable { ++count; } public int getCount() { return count; }
}
This advice does not change the execution path. If it throws an exception, it is thrown up the interceptor chain instead of the return value.
Introduction Advice
Spring將Introduction Advice看成一種特殊的攔截器處理。
Introduction requires an IntroductionAdvisor and an IntroductionInterceptor that implement the following interface:
public interface IntroductionInterceptor extends MethodInterceptor {
boolean implementsInterface(Class intf);
}
The invoke() method inherited from the AOP Alliance MethodInterceptor interface must implement the introduction. That is, if the invoked method is on an introduced interface, the introduction interceptor is responsible for handling the method call — it cannot invoke proceed().
ntroduction Advice不能用於任何pointcut,其僅能用於類上而不是方法上。
You can only use introduction advice with the IntroductionAdvisor, which has the following methods:
public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
ClassFilter getClassFilter(); void validateInterfaces() throws IllegalArgumentException;
}
public interface IntroductionInfo {
Class[] getInterfaces();
}
There is no MethodMatcher and, hence, no Pointcut associated with introduction advice. Only class filtering is logical.
The getInterfaces() method returns the interfaces introduced by this advisor.
The validateInterfaces() method is used internally to see whether or not the introduced interfaces can be implemented by the configured IntroductionInterceptor.
以下示例中,咱們但願將以下接口introduce給一個或者多個對象:
public interface Lockable {
void lock();
void unlock();
boolean locked();
}
咱們但願將對象轉型爲能夠lock(無論對象的類型),而且能夠調用lock()和unlock()方法。在調用lock()方法後,咱們但願對於對象調用的setter方法都會拋出LockedException(這是Spring AOP的一個示例,能夠在不用瞭解對象結構的狀況下加強對象)。
首先,咱們須要定義一個IntroductionInterceptor,能夠繼承org.springframework.aop.support.DelegatingIntroductionInterceptor(通常狀況下均可以繼承這個類)。
DelegatingIntroductionInterceptor用於將introduction委派給introduced接口的實際實現類。
The DelegatingIntroductionInterceptor is designed to delegate an introduction to an actual implementation of the introduced interfaces, concealing the use of interception to do so. You can set the delegate to any object using a constructor argument. The default delegate (when the no-argument constructor is used) is this. Thus, in the next example, the delegate is the LockMixin subclass of DelegatingIntroductionInterceptor. Given a delegate (by default, itself), a DelegatingIntroductionInterceptor instance looks for all interfaces implemented by the delegate (other than IntroductionInterceptor) and supports introductions against any of them. Subclasses such as LockMixin can call the suppressInterface(Class intf) method to suppress interfaces that should not be exposed. However, no matter how many interfaces an IntroductionInterceptor is prepared to support, the IntroductionAdvisor used controls which interfaces are actually exposed. An introduced interface conceals any implementation of the same interface by the target.
Thus, LockMixin extends DelegatingIntroductionInterceptor and implements Lockable itself. The superclass automatically picks up that Lockable can be supported for introduction, so we do not need to specify that. We could introduce any number of interfaces in this way.
Note the use of the locked instance variable. This effectively adds additional state to that held in the target object.
The following example shows the example LockMixin class:
public class LockMixin extends DelegatingIntroductionInterceptor implements Lockable {
private boolean locked; public void lock() { this.locked = true; } public void unlock() { this.locked = false; } public boolean locked() { return this.locked; } public Object invoke(MethodInvocation invocation) throws Throwable { if (locked() && invocation.getMethod().getName().indexOf("set") == 0) { throw new LockedException(); } return super.invoke(invocation); }
}
Often, you need not override the invoke() method. The DelegatingIntroductionInterceptor implementation (which calls the delegate method if the method is introduced, otherwise proceeds towards the join point) usually suffices. In the present case, we need to add a check: no setter method can be invoked if in locked mode.
The required introduction only needs to hold a distinct LockMixin instance and specify the introduced interfaces (in this case, only Lockable). A more complex example might take a reference to the introduction interceptor (which would be defined as a prototype). In this case, there is no configuration relevant for a LockMixin, so we create it by using new. The following example shows our LockMixinAdvisor class:
public class LockMixinAdvisor extends DefaultIntroductionAdvisor {
public LockMixinAdvisor() { super(new LockMixin(), Lockable.class); }
}
We can apply this advisor very simply, because it requires no configuration. (However, it is impossible to use an IntroductionInterceptor without an IntroductionAdvisor.) As usual with introductions, the advisor must be per-instance, as it is stateful. We need a different instance of LockMixinAdvisor, and hence LockMixin, for each advised object. The advisor comprises part of the advised object’s state.
We can apply this advisor programmatically by using the Advised.addAdvisor() method or (the recommended way) in XML configuration, as any other advisor. All proxy creation choices discussed below, including 「auto proxy creators,」 correctly handle introductions and stateful mixins.
8.3. The Advisor API in Spring
In Spring, an Advisor is an aspect that contains only a single advice object associated with a pointcut expression.
Apart from the special case of introductions, any advisor can be used with any advice. org.springframework.aop.support.DefaultPointcutAdvisor is the most commonly used advisor class. It can be used with a MethodInterceptor, BeforeAdvice, or ThrowsAdvice.
It is possible to mix advisor and advice types in Spring in the same AOP proxy. For example, you could use an interception around advice, throws advice, and before advice in one proxy configuration. Spring automatically creates the necessary interceptor chain.
8.4. Using the ProxyFactoryBean to Create AOP Proxies
If you use the Spring IoC container (an ApplicationContext or BeanFactory) for your business objects (and you should be!), you want to use one of Spring’s AOP FactoryBean implementations. (Remember that a factory bean introduces a layer of indirection, letting it create objects of a different type.)
The Spring AOP support also uses factory beans under the covers.
The basic way to create an AOP proxy in Spring is to use the org.springframework.aop.framework.ProxyFactoryBean. This gives complete control over the pointcuts, any advice that applies, and their ordering. However, there are simpler options that are preferable if you do not need such control.
8.4.1. Basics
The ProxyFactoryBean, like other Spring FactoryBean implementations, introduces a level of indirection. If you define a ProxyFactoryBean named foo, objects that reference foo do not see the ProxyFactoryBean instance itself but an object created by the implementation of the getObject() method in the ProxyFactoryBean . This method creates an AOP proxy that wraps a target object.
One of the most important benefits of using a ProxyFactoryBean or another IoC-aware class to create AOP proxies is that advices and pointcuts can also be managed by IoC. This is a powerful feature, enabling certain approaches that are hard to achieve with other AOP frameworks. For example, an advice may itself reference application objects (besides the target, which should be available in any AOP framework), benefiting from all the pluggability provided by Dependency Injection.
8.4.2. JavaBean Properties
In common with most FactoryBean implementations provided with Spring, the ProxyFactoryBean class is itself a JavaBean. Its properties are used to:
Specify the target you want to proxy.
Specify whether to use CGLIB (described later and see also JDK- and CGLIB-based proxies).
Some key properties are inherited from org.springframework.aop.framework.ProxyConfig (the superclass for all AOP proxy factories in Spring). These key properties include the following:
proxyTargetClass: true if the target class is to be proxied, rather than the target class’s interfaces. If this property value is set to true, then CGLIB proxies are created (but see also JDK- and CGLIB-based proxies).
optimize: Controls whether or not aggressive optimizations are applied to proxies created through CGLIB. You should not blithely use this setting unless you fully understand how the relevant AOP proxy handles optimization. This is currently used only for CGLIB proxies. It has no effect with JDK dynamic proxies.
frozen: If a proxy configuration is frozen, changes to the configuration are no longer allowed. This is useful both as a slight optimization and for those cases when you do not want callers to be able to manipulate the proxy (through the Advised interface) after the proxy has been created. The default value of this property is false, so changes (such as adding additional advice) are allowed.
exposeProxy: Determines whether or not the current proxy should be exposed in a ThreadLocal so that it can be accessed by the target. If a target needs to obtain the proxy and the exposeProxy property is set to true, the target can use the AopContext.currentProxy() method.
Other properties specific to ProxyFactoryBean include the following:
proxyInterfaces: An array of String interface names. If this is not supplied, a CGLIB proxy for the target class is used (but see also JDK- and CGLIB-based proxies).
interceptorNames: A String array of Advisor, interceptor, or other advice names to apply. Ordering is significant, on a first come-first served basis. That is to say that the first interceptor in the list is the first to be able to intercept the invocation.
The names are bean names in the current factory, including bean names from ancestor factories. You cannot mention bean references here, since doing so results in the ProxyFactoryBean ignoring the singleton setting of the advice.
You can append an interceptor name with an asterisk (*). Doing so results in the application of all advisor beans with names that start with the part before the asterisk to be applied. You can find an example of using this feature in Using 「Global」 Advisors.
singleton: Whether or not the factory should return a single object, no matter how often the getObject() method is called. Several FactoryBean implementations offer such a method. The default value is true. If you want to use stateful advice - for example, for stateful mixins - use prototype advices along with a singleton value of false.
8.4.3. JDK- and CGLIB-based proxies
This section serves as the definitive documentation on how the ProxyFactoryBean chooses to create either a JDK-based proxy or a CGLIB-based proxy for a particular target object (which is to be proxied).
The behavior of the ProxyFactoryBean with regard to creating JDK- or CGLIB-based proxies changed between versions 1.2.x and 2.0 of Spring. The ProxyFactoryBean now exhibits similar semantics with regard to auto-detecting interfaces as those of the TransactionProxyFactoryBean class.
If the class of a target object that is to be proxied (hereafter simply referred to as the target class) does not implement any interfaces, a CGLIB-based proxy is created. This is the easiest scenario, because JDK proxies are interface-based, and no interfaces means JDK proxying is not even possible. You can plug in the target bean and specify the list of interceptors by setting the interceptorNames property. Note that a CGLIB-based proxy is created even if the proxyTargetClass property of the ProxyFactoryBean has been set to false. (Doing so makes no sense and is best removed from the bean definition, because it is, at best, redundant, and, at worst confusing.)
If the target class implements one (or more) interfaces, the type of proxy that is created depends on the configuration of the ProxyFactoryBean.
If the proxyTargetClass property of the ProxyFactoryBean has been set to true, a CGLIB-based proxy is created. This makes sense and is in keeping with the principle of least surprise. Even if the proxyInterfaces property of the ProxyFactoryBean has been set to one or more fully qualified interface names, the fact that the proxyTargetClass property is set to true causes CGLIB-based proxying to be in effect.
If the proxyInterfaces property of the ProxyFactoryBean has been set to one or more fully qualified interface names, a JDK-based proxy is created. The created proxy implements all of the interfaces that were specified in the proxyInterfaces property. If the target class happens to implement a whole lot more interfaces than those specified in the proxyInterfaces property, that is all well and good, but those additional interfaces are not implemented by the returned proxy.
If the proxyInterfaces property of the ProxyFactoryBean has not been set, but the target class does implement one (or more) interfaces, the ProxyFactoryBean auto-detects the fact that the target class does actually implement at least one interface, and a JDK-based proxy is created. The interfaces that are actually proxied are all of the interfaces that the target class implements. In effect, this is the same as supplying a list of each and every interface that the target class implements to the proxyInterfaces property. However, it is significantly less work and less prone to typographical errors.
8.4.4. Proxying Interfaces
Consider a simple example of ProxyFactoryBean in action. This example involves:
A target bean that is proxied. This is the personTarget bean definition in the example.
An Advisor and an Interceptor used to provide advice.
An AOP proxy bean definition to specify the target object (the personTarget bean), the interfaces to proxy, and the advices to apply.
The following listing shows the example:
<property name="target" ref="personTarget"/> <property name="interceptorNames"> <list> <value>myAdvisor</value> <value>debugInterceptor</value> </list> </property>
Note that the interceptorNames property takes a list of String, which holds the bean names of the interceptors or advisors in the current factory. You can use advisors, interceptors, before, after returning, and throws advice objects. The ordering of advisors is significant.
You might be wondering why the list does not hold bean references. The reason for this is that, if the singleton property of the ProxyFactoryBean is set to false, it must be able to return independent proxy instances. If any of the advisors is itself a prototype, an independent instance would need to be returned, so it is necessary to be able to obtain an instance of the prototype from the factory. Holding a reference is not sufficient.
The person bean definition shown earlier can be used in place of a Person implementation, as follows:
Person person = (Person) factory.getBean("person");
Other beans in the same IoC context can express a strongly typed dependency on it, as with an ordinary Java object. The following example shows how to do so:
The PersonUser class in this example exposes a property of type Person. As far as it is concerned, the AOP proxy can be used transparently in place of a 「real」 person implementation. However, its class would be a dynamic proxy class. It would be possible to cast it to the Advised interface (discussed later).
You can conceal the distinction between target and proxy by using an anonymous inner bean. Only the ProxyFactoryBean definition is different. The advice is included only for completeness. The following example shows how to use an anonymous inner bean:
Using an anonymous inner bean has the advantage that there is only one object of type Person. This is useful if we want to prevent users of the application context from obtaining a reference to the un-advised object or need to avoid any ambiguity with Spring IoC autowiring. There is also, arguably, an advantage in that the ProxyFactoryBean definition is self-contained. However, there are times when being able to obtain the un-advised target from the factory might actually be an advantage (for example, in certain test scenarios).
8.4.5. Proxying Classes
What if you need to proxy a class, rather than one or more interfaces?
Imagine that in our earlier example, there was no Person interface. We needed to advise a class called Person that did not implement any business interface. In this case, you can configure Spring to use CGLIB proxying rather than dynamic proxies. To do so, set the proxyTargetClass property on the ProxyFactoryBean shown earlier to true. While it is best to program to interfaces rather than classes, the ability to advise classes that do not implement interfaces can be useful when working with legacy code. (In general, Spring is not prescriptive. While it makes it easy to apply good practices, it avoids forcing a particular approach.)
If you want to, you can force the use of CGLIB in any case, even if you do have interfaces.
CGLIB proxying works by generating a subclass of the target class at runtime. Spring configures this generated subclass to delegate method calls to the original target. The subclass is used to implement the Decorator pattern, weaving in the advice.
CGLIB proxying should generally be transparent to users. However, there are some issues to consider:
Final methods cannot be advised, as they cannot be overridden.
There is no need to add CGLIB to your classpath. As of Spring 3.2, CGLIB is repackaged and included in the spring-core JAR. In other words, CGLIB-based AOP works 「out of the box」, as do JDK dynamic proxies.
There is little performance difference between CGLIB proxying and dynamic proxies. As of Spring 1.0, dynamic proxies are slightly faster. However, this may change in the future. Performance should not be a decisive consideration in this case.
8.4.6. Using 「Global」 Advisors
By appending an asterisk to an interceptor name, all advisors with bean names that match the part before the asterisk are added to the advisor chain. This can come in handy if you need to add a standard set of 「global」 advisors. The following example defines two global advisors:
8.5. Concise Proxy Definitions
Especially when defining transactional proxies, you may end up with many similar proxy definitions. The use of parent and child bean definitions, along with inner bean definitions, can result in much cleaner and more concise proxy definitions.
First, we create a parent, template, bean definition for the proxy, as follows:
This is never instantiated itself, so it can actually be incomplete. Then, each proxy that needs to be created is a child bean definition, which wraps the target of the proxy as an inner bean definition, since the target is never used on its own anyway. The following example shows such a child bean:
You can override properties from the parent template. In the following example, we override the transaction propagation settings:
Note that in the parent bean example, we explicitly marked the parent bean definition as being abstract by setting the abstract attribute to true, as described previously, so that it may not actually ever be instantiated. Application contexts (but not simple bean factories), by default, pre-instantiate all singletons. Therefore, it is important (at least for singleton beans) that, if you have a (parent) bean definition that you intend to use only as a template, and this definition specifies a class, you must make sure to set the abstract attribute to true. Otherwise, the application context actually tries to pre-instantiate it.
8.6. Creating AOP Proxies Programmatically with the ProxyFactory
It is easy to create AOP proxies programmatically with Spring. This lets you use Spring AOP without dependency on Spring IoC.
The interfaces implemented by the target object are automatically proxied. The following listing shows creation of a proxy for a target object, with one interceptor and one advisor:
ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);
factory.addAdvice(myMethodInterceptor);
factory.addAdvisor(myAdvisor);
MyBusinessInterface tb = (MyBusinessInterface) factory.getProxy();
The first step is to construct an object of type org.springframework.aop.framework.ProxyFactory. You can create this with a target object, as in the preceding example, or specify the interfaces to be proxied in an alternate constructor.
You can add advices (with interceptors as a specialized kind of advice), advisors, or both and manipulate them for the life of the ProxyFactory. If you add an IntroductionInterceptionAroundAdvisor, you can cause the proxy to implement additional interfaces.
There are also convenience methods on ProxyFactory (inherited from AdvisedSupport) that let you add other advice types, such as before and throws advice. AdvisedSupport is the superclass of both ProxyFactory and ProxyFactoryBean.
Integrating AOP proxy creation with the IoC framework is best practice in most applications. We recommend that you externalize configuration from Java code with AOP, as you should in general.
8.7. Manipulating Advised Objects
However you create AOP proxies, you can manipulate them BY using the org.springframework.aop.framework.Advised interface. Any AOP proxy can be cast to this interface, no matter which other interfaces it implements. This interface includes the following methods:
Advisor[] getAdvisors();
void addAdvice(Advice advice) throws AopConfigException;
void addAdvice(int pos, Advice advice) throws AopConfigException;
void addAdvisor(Advisor advisor) throws AopConfigException;
void addAdvisor(int pos, Advisor advisor) throws AopConfigException;
int indexOf(Advisor advisor);
boolean removeAdvisor(Advisor advisor) throws AopConfigException;
void removeAdvisor(int index) throws AopConfigException;
boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;
boolean isFrozen();
The getAdvisors() method returns an Advisor for every advisor, interceptor, or other advice type that has been added to the factory. If you added an Advisor, the returned advisor at this index is the object that you added. If you added an interceptor or other advice type, Spring wrapped this in an advisor with a pointcut that always returns true. Thus, if you added a MethodInterceptor, the advisor returned for this index is a DefaultPointcutAdvisor that returns your MethodInterceptor and a pointcut that matches all classes and methods.
The addAdvisor() methods can be used to add any Advisor. Usually, the advisor holding pointcut and advice is the generic DefaultPointcutAdvisor, which you can use with any advice or pointcut (but not for introductions).
By default, it is possible to add or remove advisors or interceptors even once a proxy has been created. The only restriction is that it is impossible to add or remove an introduction advisor, as existing proxies from the factory do not show the interface change. (You can obtain a new proxy from the factory to avoid this problem.)
The following example shows casting an AOP proxy to the Advised interface and examining and manipulating its advice:
Advised advised = (Advised) myObject;
Advisor[] advisors = advised.getAdvisors();
int oldAdvisorCount = advisors.length;
System.out.println(oldAdvisorCount + " advisors");
// Add an advice like an interceptor without a pointcut
// Will match all proxied methods
// Can use for interceptors, before, after returning or throws advice
advised.addAdvice(new DebugInterceptor());
// Add selective advice using a pointcut
advised.addAdvisor(new DefaultPointcutAdvisor(mySpecialPointcut, myAdvice));
assertEquals("Added two advisors", oldAdvisorCount + 2, advised.getAdvisors().length);
It is questionable whether it is advisable (no pun intended) to modify advice on a business object in production, although there are, no doubt, legitimate usage cases. However, it can be very useful in development (for example, in tests). We have sometimes found it very useful to be able to add test code in the form of an interceptor or other advice, getting inside a method invocation that we want to test. (For example, the advice can get inside a transaction created for that method, perhaps to run SQL to check that a database was correctly updated, before marking the transaction for roll back.)
Depending on how you created the proxy, you can usually set a frozen flag. In that case, the Advised isFrozen() method returns true, and any attempts to modify advice through addition or removal results in an AopConfigException. The ability to freeze the state of an advised object is useful in some cases (for example, to prevent calling code removing a security interceptor). It may also be used in Spring 1.1 to allow aggressive optimization if runtime advice modification is known not to be required.
8.8. Using the "auto-proxy" facility
So far, we have considered explicit creation of AOP proxies by using a ProxyFactoryBean or similar factory bean.
Spring also lets us use 「auto-proxy」 bean definitions, which can automatically proxy selected bean definitions. This is built on Spring’s 「bean post processor」 infrastructure, which enables modification of any bean definition as the container loads.
In this model, you set up some special bean definitions in your XML bean definition file to configure the auto-proxy infrastructure. This lets you declare the targets eligible for auto-proxying. You neet not use ProxyFactoryBean.
There are two ways to do this:
By using an auto-proxy creator that refers to specific beans in the current context.
A special case of auto-proxy creation that deserves to be considered separately: auto-proxy creation driven by source-level metadata attributes.
8.8.1. Auto-proxy Bean Definitions
This section covers the auto-proxy creators provided by the org.springframework.aop.framework.autoproxy package.
BeanNameAutoProxyCreator
The BeanNameAutoProxyCreator class is a BeanPostProcessor that automatically creates AOP proxies for beans with names that match literal values or wildcards. The following example shows how to create a BeanNameAutoProxyCreator bean:
As with ProxyFactoryBean, there is an interceptorNames property rather than a list of interceptors, to allow correct behavior for prototype advisors. Named 「interceptors」 can be advisors or any advice type.
As with auto-proxying in general, the main point of using BeanNameAutoProxyCreator is to apply the same configuration consistently to multiple objects, with minimal volume of configuration. It is a popular choice for applying declarative transactions to multiple objects.
Bean definitions whose names match, such as jdkMyBean and onlyJdk in the preceding example, are plain old bean definitions with the target class. An AOP proxy is automatically created by the BeanNameAutoProxyCreator. The same advice is applied to all matching beans. Note that, if advisors are used (rather than the interceptor in the preceding example), the pointcuts may apply differently to different beans.
DefaultAdvisorAutoProxyCreator
A more general and extremely powerful auto-proxy creator is DefaultAdvisorAutoProxyCreator. This automagically applies eligible advisors in the current context, without the need to include specific bean names in the auto-proxy advisor’s bean definition. It offers the same merit of consistent configuration and avoidance of duplication as BeanNameAutoProxyCreator.
Using this mechanism involves:
Specifying a DefaultAdvisorAutoProxyCreator bean definition.
Specifying any number of advisors in the same or related contexts. Note that these must be advisors, not interceptors or other advices. This is necessary, because there must be a pointcut to evaluate, to check the eligibility of each advice to candidate bean definitions.
The DefaultAdvisorAutoProxyCreator automatically evaluates the pointcut contained in each advisor, to see what (if any) advice it should apply to each business object (such as businessObject1 and businessObject2 in the example).
This means that any number of advisors can be applied automatically to each business object. If no pointcut in any of the advisors matches any method in a business object, the object is not proxied. As bean definitions are added for new business objects, they are automatically proxied if necessary.
Auto-proxying in general has the advantage of making it impossible for callers or dependencies to obtain an un-advised object. Calling getBean("businessObject1") on this ApplicationContext returns an AOP proxy, not the target business object. (The 「inner bean」 idiom shown earlier also offers this benefit.)
The following example creates a DefaultAdvisorAutoProxyCreator bean and the other elements discussed in this section:
The DefaultAdvisorAutoProxyCreator is very useful if you want to apply the same advice consistently to many business objects. Once the infrastructure definitions are in place, you can add new business objects without including specific proxy configuration. You can also easily drop in additional aspects (for example, tracing or performance monitoring aspects) with minimal change to configuration.
The DefaultAdvisorAutoProxyCreator offers support for filtering (by using a naming convention so that only certain advisors are evaluated, which allows the use of multiple, differently configured, AdvisorAutoProxyCreators in the same factory) and ordering. Advisors can implement the org.springframework.core.Ordered interface to ensure correct ordering if this is an issue. The TransactionAttributeSourceAdvisor used in the preceding example has a configurable order value. The default setting is unordered.
8.9. Using TargetSource Implementations
Spring offers the concept of a TargetSource, expressed in the org.springframework.aop.TargetSource interface. This interface is responsible for returning the 「target object」 that implements the join point. The TargetSource implementation is asked for a target instance each time the AOP proxy handles a method invocation.
Developers who use Spring AOP do not normally need to work directly with TargetSource implementations, but this provides a powerful means of supporting pooling, hot swappable, and other sophisticated targets. For example, a pooling TargetSource can return a different target instance for each invocation, by using a pool to manage instances.
If you do not specify a TargetSource, a default implementation is used to wrap a local object. The same target is returned for each invocation (as you would expect).
The rest of this section describes the standard target sources provided with Spring and how you can use them.
When using a custom target source, your target will usually need to be a prototype rather than a singleton bean definition. This allows Spring to create a new target instance when required.
8.9.1. Hot-swappable Target Sources
The org.springframework.aop.target.HotSwappableTargetSource exists to let the target of an AOP proxy be switched while letting callers keep their references to it.
Changing the target source’s target takes effect immediately. The HotSwappableTargetSource is thread-safe.
You can change the target by using the swap() method on HotSwappableTargetSource, as the follow example shows:
HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper");
Object oldTarget = swapper.swap(newTarget);
The following example shows the required XML definitions:
The preceding swap() call changes the target of the swappable bean. Clients that hold a reference to that bean are unaware of the change but immediately start hitting the new target.
Although this example does not add any advice (it is not necessary to add advice to use a TargetSource), any TargetSource can be used in conjunction with arbitrary advice.
8.9.2. Pooling Target Sources
Using a pooling target source provides a similar programming model to stateless session EJBs, in which a pool of identical instances is maintained, with method invocations going to free objects in the pool.
A crucial difference between Spring pooling and SLSB pooling is that Spring pooling can be applied to any POJO. As with Spring in general, this service can be applied in a non-invasive way.
Spring provides support for Commons Pool 2.2, which provides a fairly efficient pooling implementation. You need the commons-pool Jar on your application’s classpath to use this feature. You can also subclass org.springframework.aop.target.AbstractPoolingTargetSource to support any other pooling API.
Commons Pool 1.5+ is also supported but is deprecated as of Spring Framework 4.2.
The following listig shows an example configuration:
... properties omitted
Note that the target object (businessObjectTarget in the preceding example) must be a prototype. This lets the PoolingTargetSource implementation create new instances of the target to grow the pool as necessary. See the javadoc of AbstractPoolingTargetSource and the concrete subclass you wish to use for information about its properties. maxSize is the most basic and is always guaranteed to be present.
In this case, myInterceptor is the name of an interceptor that would need to be defined in the same IoC context. However, you need not specify interceptors to use pooling. If you want only pooling and no other advice, do not set the interceptorNames property at all.
You can configure Spring to be able to cast any pooled object to the org.springframework.aop.target.PoolingConfig interface, which exposes information about the configuration and current size of the pool through an introduction. You need to define an advisor similar to the following:
This advisor is obtained by calling a convenience method on the AbstractPoolingTargetSource class, hence the use of MethodInvokingFactoryBean. This advisor’s name (poolConfigAdvisor, here) must be in the list of interceptors names in the ProxyFactoryBean that exposes the pooled object.
The cast is defined as follows:
PoolingConfig conf = (PoolingConfig) beanFactory.getBean("businessObject");
System.out.println("Max pool size is " + conf.getMaxSize());
Pooling stateless service objects is not usually necessary. We do not believe it should be the default choice, as most stateless objects are naturally thread safe, and instance pooling is problematic if resources are cached.
Simpler pooling is available by using auto-proxying. You can set the TargetSource implementations used by any auto-proxy creator.
8.9.3. Prototype Target Sources
Setting up a 「prototype」 target source is similar to setting up a pooling TargetSource. In this case, a new instance of the target is created on every method invocation. Although the cost of creating a new object is not high in a modern JVM, the cost of wiring up the new object (satisfying its IoC dependencies) may be more expensive. Thus, you should not use this approach without very good reason.
To do this, you could modify the poolTargetSource definition shown earlier as follows (we also changed the name, for clarity):
The only property is the name of the target bean. Inheritance is used in the TargetSource implementations to ensure consistent naming. As with the pooling target source, the target bean must be a prototype bean definition.
8.9.4. ThreadLocal Target Sources
ThreadLocal target sources are useful if you need an object to be created for each incoming request (per thread that is). The concept of a ThreadLocal provides a JDK-wide facility to transparently store a resource alongside a thread. Setting up a ThreadLocalTargetSource is pretty much the same as was explained for the other types of target source, as the following example shows:
ThreadLocal instances come with serious issues (potentially resulting in memory leaks) when incorrectly using them in multi-threaded and multi-classloader environments. You should always consider wrapping a threadlocal in some other class and never directly use the ThreadLocal itself (except in the wrapper class). Also, you should always remember to correctly set and unset (where the latter simply involves a call to ThreadLocal.set(null)) the resource local to the thread. Unsetting should be done in any case, since not unsetting it might result in problematic behavior. Spring’s ThreadLocal support does this for you and should always be considered in favor of using ThreadLocal instances without other proper handling code.
8.10. Defining New Advice Types
Spring AOP is designed to be extensible. While the interception implementation strategy is presently used internally, it is possible to support arbitrary advice types in addition to the interception around advice, before, throws advice, and after returning advice.
The org.springframework.aop.framework.adapter package is an SPI package that lets support for new custom advice types be added without changing the core framework. The only constraint on a custom Advice type is that it must implement the org.aopalliance.aop.Advice marker interface.
See the org.springframework.aop.framework.adapter javadoc for further information.