切點一
package com.spring.apo;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
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(2)
@Aspect
@Component
public class LoggingAspect {
/**
* 定義一個方法,用於聲明切點表達式
* 一般情況,這是一個空方法
*/
@Pointcut("execution(public int com.spring.apo.ArtthemticCalculator.*(..))")
public void declareJoinPointExpression(){
}
/**
* 在com.spring.apo.ArtthemticCalculator
* 的每一個方法執行之前 執行的處理
*/
@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("【日誌出力】前置通知方法名: " + methodName + " 方法參數為:" + Arrays.asList(args));
}
/**
* 在com.spring.apo.ArtthemticCalculator
* 的每一個方法執行之後 執行的處理
* 無論正常還是異常終了
* 不能接受到返回值
*/
@After("declareJoinPointExpression()")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("後置通知方法名: " + methodName + " 方法返回值不能取得。");
}
/**
* 在com.spring.apo.ArtthemticCalculator
* 的每一個方法執行之後 執行的處理
* 僅僅是正常終了
* 可以接受到返回值
* @param joinPoint
*/
@AfterReturning(value = "declareJoinPointExpression()",
returning="result")
public void afterReturning(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("返回通知方法名: " + methodName + " 方法返回值可以取得,且返回值爲:" + result);
}
/**
* 在com.spring.apo.ArtthemticCalculator
* 的每一個方法執行之後 執行的處理
* 僅僅是異常終了
* 可以接受到返回值
* @param joinPoint
*/
@AfterThrowing(value = "declareJoinPointExpression()",
throwing="ex")
public void afterThrowing(JoinPoint joinPoint,Exception ex){
String methodName = joinPoint.getSignature().getName();
System.out.println("異常通知方法名: " + methodName + " 方法異常終了,且異常爲:" + ex);
}
}
另一個切面 引用 該切面的聲明
package com.spring.apo;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1)
@Aspect
@Component
public class VlidationAspect {
@Before("com.spring.apo.LoggingAspect.declareJoinPointExpression()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
System.out.println("【數據檢證】前置通知方法名: " + methodName + " 方法參數為:" + Arrays.asList(args));
}
}