直接上代碼java
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.aspectj.lang.annotation.Pointcut; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 切面類 * 1.須要將該類放入到IOC容器中 * 2.再將它申明爲一個切面 */ @Order(2) @Aspect @Component public class LoggingAspect { /** * 定義一個方法,聲明切入點表達式 * 使用@Pointcut用來申明切入點表達式 */ @Pointcut("execution(* com.test.aop.impl.CalculatorImpl.*(int,int))") public void declareJointPointExpression() { } //環繞通知 @Around("declareJointPointExpression()") 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; } }
外部使用該申明方法spring
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("com.test.aop.impl.LoggingAspect.declareJointPointExpression()") public void validateArgs(JoinPoint joinPoint) { System.out.println("validate:"+Arrays.asList(joinPoint.getArgs())); } }