Advice的几种定义方式
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() {
// ...
}
}
Advice支持in-place pointcut expression,直接将PointCut的表达式写在Advice注解里:
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
在切点方法正常返回后执行。注意:一定是正常返回后。
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() {
// ...
}
}
支持绑定切点方法的返回值,returning后变量名需要跟doAccessCheck中的参数名保持一致,同时,retVal的类型还用来限制过滤切点的条件,切点处的方法必须匹配相应的返回值才算符合条件:
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
在切点方法抛出异常之后执行。
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后面的参数名称需要跟doRecoveryActions的参数名称一致。
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
跟java的finally的意义一样,不管切点处的方法正常返回还是抛出异常,都一定会在之后执行的逻辑。适合用于释放资源等。
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
在切点方法执行之前和之后执行工作,并确定方法何时、如何、甚至是否真正执行。
Always use the least powerful form of advice that meets your requirements (that is, do not use around advice if before advice would do).
Around advice is often used if you need to share state before and after a method execution in a thread-safe manner (starting and stopping a timer, for example)
@Around注释的方法通过ProceedingJoinPoint pjp参数来执行被代理的切点方法。pjp.proceed()执行的就是切点方法,pjp.proceed()还有个重载方法是pjp.proceed(Object[] objects),可以通过使用后面的重载方法给切点方法传入参数,传入的参数会覆盖掉原参数(注意,这里传递的参数使用Full AspectJ和Spring AOP的语义是不同的,不过可以通过后面讲解绑定参数的方式做到兼容)。doBasicProfiling的返回值最终作为切点方法的返回值返回。所以,通过@Around注解是有能力篡改切点方法的输入参数和返回值的。
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;
}
}
总之,因为切点方法是通过ProceedingJoinPoint参数调用的,所以@Around可以完全控制切点方法的访问,甚至可以在某些条件满足的情况下不调用切点方法也是完全支持的。
Advice Parameters
Access to the Current JoinPoint
所有的Advice方法都可以通过传入org.aspectj.lang.JoinPoint参数来通过以下方法访问切点的具体信息(@Around必须传入ProceedingJoinPoint,ProceedingJoinPoint是JoinPoint子类):
- 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
在前面已经讲解了如何绑定返回值和异常对象。下面的实例给出如何绑定切点方法的参数,将参数传递给Advice方法:
@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
public void validateAccount(Account account) {
// ...
}
args(account,..)在这里有两个用途。第一,限制匹配到的切点方法至少包含一个参数,并且参数类型为Account;第二,切点方法的Account参数对象可以传递给validateAccount使用。
与上面等价的定义方式如下:
@Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
private void accountDataAccessOperation(Account account) {}
@Before("accountDataAccessOperation(account)")
public void validateAccount(Account account) {
// ...
}
this,target,annotations (@within, @target, @annotation, and @args)也可以用来绑定参数。
The proxy object ( this), target object ( target), and annotations ( @within, @target, @annotation, and @args) can all be bound in a similar fashion.
定义Auditable注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auditable {
AuditCode value();
}
示例中,用来匹配使用Auditable注解的公共方法作为切点,同时将注解绑定至参数。
@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 param);
}
以下示例用来匹配上面Sample
@Before("execution(* ..Sample+.sampleGenericMethod(*)) && args(param)")
public void beforeSampleMethod(MyType param) {
// Advice implementation
}
但是对于集合来说,以下的切点定义是不允许的:
@Before("execution(* ..Sample+.sampleGenericCollectionMethod(*)) && args(param)")
public void beforeSampleMethod(Collection param) {
// Advice implementation
}
如果非要使用集合,那么可以定义Collection>,由用户自己来针对集合中的类型进行检查和转换。
Proceeding with Arguments
@Around("execution(List find*(..)) && " +
"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});
}
Advice Ordering
多个Advice的优先级设置以及需要注意的地方。
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