方法設計:git
// spring提供了ProceedingJoinPoint接口用來讓咱們獲取切入點的信息 public Object aroundLogging(ProceedingJoinPoint pjp) { try { System.out.println("前置 ..."); Object ret = pjp.proceed(pjp.getArgs()); System.out.println("後置 ..."); return ret; } catch (Throwable throwable) { System.out.println("異常 ..."); throw new RuntimeException(throwable); } finally { System.out.println("最終 ..."); } }
配置切入點github
<aop:config> <!-- 配置切入點 --> <aop:pointcut id="logPointcut" expression="execution(* cn.ann.service..*.*(..))"/> </aop:config>
aop配置代碼spring
<!-- 配置AOP --> <aop:config> <!-- 配置切入點 --> <aop:pointcut id="logPointcut" expression="execution(* cn.ann.service..*.*(..))"/> <!-- 配置切面 --> <aop:aspect id="logAdvice" ref="logger"> <!-- 前置通知 <aop:before method="beforeLogging" pointcut-ref="logPointcut"/> --> <!-- 後置通知 <aop:after-returning method="afterReturningLogging" pointcut-ref="logPointcut"/> --> <!-- 異常通知 <aop:after-throwing method="afterThrowingLogging" pointcut-ref="logPointcut"/> --> <!-- 最終通知 <aop:after method="afterLogging" pointcut-ref="logPointcut"/> --> <!-- 環繞通知 --> <aop:around method="aroundLogging" pointcut-ref="logPointcut"/> </aop:aspect> </aop:config>
<context:component-scan base-package="cn.ann"/>
<aop:aspectj-autoproxy/>
配置切入點:express
@Pointcut("execution(* cn.ann.service..*.*(..))") private void logPointcut(){}
配置通知設計
@Before("logPointcut()") public void beforeLogging(){ System.out.println("before logging run..."); } @AfterReturning("logPointcut()") public void afterReturningLogging(){ System.out.println("afterReturning logging run..."); } @AfterThrowing("logPointcut()") public void afterThrowingLogging(){ System.out.println("afterThrowing logging run..."); } @After("logPointcut()") public void afterLogging(){ System.out.println("after logging run..."); } @Around("logPointcut()") public Object aroundLogging(ProceedingJoinPoint pjp) { try { System.out.println("前置 ..."); Object ret = pjp.proceed(); System.out.println("後置 ..."); return ret; } catch (Throwable throwable) { System.out.println("異常 ..."); throw new RuntimeException(throwable); } finally { System.out.println("最終 ..."); } }
本文代碼: 此處 的 spring03-aop代理