Spring AOP (二)

在Spring AOP初嘗試裏面,每個切面方法前面的切面都是一樣的,此處可以將它們提出處理,用一個統一的空實現的方法來表示。

將上一篇的例子修改之後,如下。


package com;


import java.util.Arrays;
import java.util.List;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


// Order 在多個切面的情況下,用來指定切面的優先級,數值越小,優先級越高
@Order(1)
@Aspect
@Component
public class ArithLoggingAspect {

// 此處方法一定要是空實現

// 類在同一個包下面的話,可以不用全類名
@Pointcut("execution(* Calculator.*(..))")
public void declarePointcut() {}


@Before("declarePointcut()")
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());

System.out.println("The method " + methodName + " begins with " + args);
}

@After("declarePointcut()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " ends");
}

// 此處returning="rtv"中的rtv與方法的參數Object rtv要名稱一致
@AfterReturning(value="declarePointcut()",returning="rtv")
public void afterReturn(JoinPoint joinPoint, Object rtv) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " return " + rtv);
}

// 此處throwing="e"指定了Exception e參數變量名
@AfterThrowing(value="declarePointcut()",throwing="e")
public void afterException(JoinPoint joinPoint,Exception e) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName + " exception ");
e.printStackTrace();
}

// @Around必須有返回值,而且返回值必須是proceed的返回值
@Around("declarePointcut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
List<Object> args = Arrays.asList(pjp.getArgs());
System.out.println("around " + args);
return pjp.proceed();
}
}


PS:如果是要引用其他類裏面的切面聲明,就在declarePointcut()前面加上類的全類名


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章