SSISO Community

시소당

AOP 예제4 - Throws Advice

package com.youngkun.aoptest;

public class ErrorBean {
   public void errorProneMethod() throws Exception{
       throw new Exception("Foo");
   }
  
   public void otherErrorProneMethod() throws IllegalArgumentException{
       throw new IllegalArgumentException("Bar");
   }
}

package com.youngkun.aoptest;

import java.lang.reflect.Method;

import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;

public class SimpleThrowsAdvice implements ThrowsAdvice{
  
   public static void main(String[] args) {
       ErrorBean errorBean = new ErrorBean();
      
       ProxyFactory pf = new ProxyFactory();
       pf.setTarget(errorBean);
       pf.addAdvice(new SimpleThrowsAdvice());
      
       ErrorBean proxy = (ErrorBean)pf.getProxy();
      
       try{
           proxy.errorProneMethod();
       }catch(Exception ignored){}
      
       try{
           proxy.otherErrorProneMethod();
       }catch(Exception ignored){}
   }
  
   public void afterThrowing(Exception ex) throws Throwable{
       System.out.println("***");
       System.out.println("Generic Exception Capture");
       System.out.println("Caught: " + ex.getClass().getName());
       System.out.println("***\n");
   }
  
   public void afterThrowing(Method method, Object[] args, Object target, IllegalArgumentException ex)
       throws Throwable{
       System.out.println("***");
       System.out.println("IllegalArgumentException Capture");
       System.out.println("Caught: "+ ex.getClass().getName());
       System.out.println("Method: "+ method.getName());
       System.out.println("***\n");
   }
}


실행 결과

***
Generic Exception Capture
Caught: java.lang.Exception
***

***
IllegalArgumentException Capture
Caught: java.lang.IllegalArgumentException
Method: otherErrorProneMethod
***

 

출처 : http://youngkun.info/95

745 view

4.0 stars