假设工程中有两个切面:验证切面和日志切面,我们需要验证切面在日志切面的前面,则需要做如下配置
验证切面如下
package com.test.aop.impl;
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 Validation {
@Before("execution(* com.test.aop.impl.CalculatorImpl.*(int,int))")
public void validateArgs(JoinPoint joinPoint) {
System.out.println("validate:"+Arrays.asList(joinPoint.getArgs()));
}
}
日志切面如下
package com.test.aop.impl;
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 切面类
* 1.需要将该类放入到IOC容器中
* 2.再将它申明为一个切面
*/
@Order(2)
@Aspect
@Component
public class LoggingAspect {
//环绕通知
@Around("execution(* com.test.aop.impl.CalculatorImpl.*(int,int))")
public Object Around(ProceedingJoinPoint proceedingJoinPoint){
Object result = null;
String methodName = proceedingJoinPoint.getSignature().getName();
try {
//前置通知
System.out.println("The method"+methodName+"begin with:"+Arrays.asList(proceedingJoinPoint.getArgs()));
result = proceedingJoinPoint.proceed();
//返回通知
System.out.println("The method" + methodName + "end with:"+result);
} catch (Throwable e) {
//异常通知
System.out.println("The method" + methodName + "occurs exception:"+e);
}
//后置通知
System.out.println("The method" + methodName + "end ");
return result;
}
}