1. 程式人生 > >Spring Aspectj 代理 前置 後置 以及 異常

Spring Aspectj 代理 前置 後置 以及 異常

  1. public interface IDog2 {  
  2.     public  void  dog();  
  3.   
  4.     public  String  run();  
  5. }  
  6. public class Dog2 implements
     IDog2 {  
  7.     public  void  dog(){  
  8.         System.out.println("===測試顧問==1dog()");  
  9.     }  
  10.   
  11.     public
     String run() {  
  12.         int resul=5/0;  
  13.         System.out.println("====測試顧問===2run()");  
  14.         return "add";  
  15.     }  
  16. }  
  17. @Aspect  
  18. public class MyAspectj {  
  19.     //前置增強  
  20.     //@Before(value = "execution(* *..springAspectj.*.*(..))")  
  21.     public  void MyBefore(){  
  22.         System.out.println("====這是前置增強====");  
  23.     }  
  24.     //後置增強  
  25.    // @AfterReturning(value = "execution(* *..springAspectj.*.*(..))")  
  26.     public  void After(){  
  27.         System.out.println("====這是後置增強====");  
  28.     }  
  29.   
  30.   
  31.     //環繞增強  相對於 後置增強 可以 改變 返回值的 內容  
  32.    // @Around(value = "execution(* *..springAspectj.*.*(..))")  
  33.      public  Object  around(ProceedingJoinPoint point) throws Throwable {  
  34.         System.out.println("==環繞前===");  
  35.         Object result = point.proceed();  
  36.         System.out.println("==環繞之後===");  
  37.         if (result!=null){  
  38.             String stu=(String)result;  
  39.             return stu.toUpperCase();  
  40.         }else {  
  41.             return  null;  
  42.         }  
  43.   
  44.     }  
  45.   
  46.   
  47.     @AfterThrowing(value = "execution(* *..springAspectj.*.*(..))")  
  48.     public  void After2(){  
  49.   
  50.         System.out.println("====這是異常====");  
  51.     }  
  52. }  
[java]  view plain  copy
  1. //Aspectj 代理  
  2. //測試 前置 後置 增強  
  3. //測試 環繞增強 可以改變 返回值  
  4. //測試 異常  
  5. @Test  
  6. public  void  aVoid3(){  
  7.     ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext09Aspectj.xml");  
  8.     IDog2 dog =(IDog2) ctx.getBean("dog2");  
  9.     dog.dog();  
  10.     System.out.println();  
  11.     String run = dog.run();  
  12.     System.out.println(run);  
  13. }