关于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

相关文章
相关标签/搜索