切点一
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));
}
}