關於spring的ThrowsAdvice (轉)


關於SPRING的AOP

aop的一個切面接口是 ThrowsAdvice,這是個標記接口,裏面沒有定義任何方法。書上說,根據spring文檔,必須定義一個 afterThrowing([Method, args, target], subclassOfThrowable) 形式的方法,前面三個參數可選,也就是你能夠寫成 afterThrowing( args, target, subclassOfThrowable) ,也能夠寫成 afterThrowing( target, subclassOfThrowable)  java

事實上若是真的這麼作,運行時會拋出 At least one handler method must be found in class 形式的異常。在確認本身沒有打錯字以後,只好去查spring2.0的手冊,才發現上面是這麼說的:方法能夠有一個或四個參數。 也就是說,不能有兩個、三個參數,方法的形式只能有兩種: afterThrowing([Method, args, target], subclassOfThrowable)  或者 afterThrowing( subclassOfThrowable) spring

以下例: app

import java.lang.reflect.Method;

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

public class ExceptionAdvisor implements ThrowsAdvice {
    public void afterThrowing(RuntimeException rx) {

    }

    /**
     * 對未知異常的處理.
     */
    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
        System.out.println("*************************************");
        System.out.println("Error happened in class: " + target.getClass().getName());
        System.out.println("Error happened in method: " + method.getName());

        for (int i = 0; i < args.length; i++) {
            System.out.println("arg[" + i + "]: " + args[i]);
        }

        System.out.println("Exception class: " + ex.getClass().getName());
        System.out.println("*************************************");
    }

    /**
     * 對NumberFormatException異常的處理
     */
    public void afterThrowing(Method method, Object[] args, Object target, NumberFormatException ex) throws Throwable {
        System.out.println("*************************************");
        System.out.println("Error happened in class: " + target.getClass().getName());
        System.out.println("Error happened in method: " + method.getName());

        for (int i = 0; i < args.length; i++) {
            System.out.println("args[" + i + "]: " + args[i]);
        }

        System.out.println("Exception class: " + ex.getClass().getName());
        System.out.println("*************************************");
    }

    public static void main(String[] args) {
        TestBean bean = new TestBean();
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(bean);
        pf.addAdvice(new ExceptionAdvisor());

        TestBean proxy = (TestBean) pf.getProxy();
        try {
            proxy.method1();
        } catch (Exception ignore) {
            System.out.println("Exception in method1 catch");
        }

        try {
            proxy.changeToNumber("amigo");
        } catch (Exception ignore) {
            System.out.println("Exception in changeToNumber catch");
        }
    }
} orm

相關文章
相關標籤/搜索