Spring框架之AOP面向切面程式設計
阿新 • • 發佈:2018-12-26
測試類:package com.jredu.aop.aspect; 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.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 切面 * @author Administrator * */ @Aspect @Component @Order(1)//優先順序:數值越小優先順序越高 public class LogAspect { /** * 切面的方法:匹配com.jredu.aop.service的所有介面或類,當中至少包含一個double型別引數的sub方法 * @param point */ @Before("execution(public double com.jredu.aop.service.*.*(double,..))") public void test(JoinPoint point){ String methodName=point.getSignature().getName(); double a = (double) point.getArgs()[0]; System.out.println("有一個double型別引數的方法:"+methodName+"的double型別引數a="+a); } /** * 當目標方法執行之前呼叫的切面方法 * @param point */ //前置日誌 @Before("execution(public double com.jredu.aop.service.*.*(double,double))") public void beforelog(JoinPoint point){ //方法名字 String methodName = point.getSignature().getName(); //引數列表 double a = (double) point.getArgs()[0]; double b = (double) point.getArgs()[1]; System.out.println("before----方法:"+methodName+"的引數a="+a+",b="+b); } //後置日誌 @After("execution(public double com.jredu.aop.service.*.*(double,double))") public void afterlog(JoinPoint point){ //方法名字 String methodName=point.getSignature().getName(); //返回結果 System.out.println("after----方法:"+methodName); } /** * 當方法執行完畢並返回結果之後的切面方法 */ @AfterReturning(pointcut="execution(* com.jredu.aop.service.*.*(..))",returning="obj") public void afterReturning(JoinPoint point,Object obj){ //方法名 String method=point.getSignature().getName(); System.out.println("after return ----- method:"+method+",return:"+obj); } /** * 當目標方法丟擲異常時會執行的方法 * @param point * @param ex */ @AfterThrowing(pointcut="execution(* com.jredu.aop.service.*.*(..))",throwing="ex") public void afterThrowing(JoinPoint point,Exception ex){ String method = point.getSignature().getName(); System.out.println("after throw ----- method:"+method+",return:"+ex.getLocalizedMessage()); } /** * 當目標方法執行前和執行後會執行該方法(環繞方法) * @param point * @throws Throwable */ @Around("execution(* com.jredu.aop.service.*.*(..))") public double around(ProceedingJoinPoint point) throws Throwable{ //執行目標方法前 String method = point.getSignature().getName(); System.out.println("before method:"+method); double d= (double) point.proceed(); //執行目標方法後,返回結果前 System.out.println("返回值是:"+d); //呼叫proceed方法,可以分割前後 System.out.println("after method:"+method); return d;//最後確定要返回的值 } }