Spring的通知(Advice)


  Spring提供了5種Advice類型:

  Interception Around:JointPoint前后調用

  Before:JointPoint前調用

  After Returning:JointPoint后調用

  Throw:JoinPoint拋出異常時調用

  Introduction:JointPoint調用完畢后調用

 

Interception Around通知

  Interception Around通知會在JoinPoint的前后執行。實現此通知的類需要實現接口MethodInterceptor,示例代碼如下:

1 public class LogInterceptor implements MethodInterceptor{
2       public Object invoke(MethodInvocation invocation invocation) throws Throwable{
3            System.out.println("開始審核數據...");
4            Object rval = invocation.proceed();
5            System.out.println("審核數據結束...");
6            return rval;
7 }       
8 }    

Before通知

只在JointPoint前執行,實現Before通知的類需要實現接口MethodBeforeAdvice,示例帶入如下:

 
        
1 public class LogBeforeAdvice implements MethodBeforeAdvice{
2       public void before(Method m,Object[] args,Object target) throw Throwable{
3        System.out.println("開始審核數據...");  
4 }
5 }
 
        

After Returning通知

  只在JointPoint之后執行,實現After Returning通知的類需要實現接口AfterReturningAdvice,示例代碼如下:

 

1 public class LogAfterAdvice implements AfterReturningAdvice{
2        public void afterReturning(Method m,Object[] args,Object target) throws Throwable{
3        System.out.println(“審核數據結束...”);
4 }
5 }

Throw通知

    只在JointPoint拋出異常時執行,實現Throw通知的類需要實現接口ThrowsAdvice,示例代碼如下:

1 public class LogThrowAdvice implements ThrowsAdvice{
2       public void afterThrowing(RemoteException ex) throws Throwable{
3          System.out.println("審核數據異常,請檢查..."+ex);
4 }
5 }

Introduction通知

  只在JointPoint調用完畢后執行,實現Introduction通知的類需要實現接口IntroductionAdvisor和接口IntroductionInterceptor

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM