抛出同志在联结点之后运行(记住Spring所谓的联结点永远是方法调用),我们通过实现ThrowsAdvise接口来时先抛出通知,在实现ThrowsAdvise接口的方法中,有两个重载的afterThrowing方法/
public void afterThrowing(Exception ex) throws Throwable{
}
public void afterThrowing(Method method,Object[] obj,Object target,IllegalArgumentException ex) throws Throwable{
}
}
两个方法的调用规则如下:
(1)Spring只会运行一个afterThrowing方法
(2)当抛出Exception,运行第一个方法,抛出IllegalArgumentException ,运行第二个方法(以本文为例)/
(3)当一个参数合两个参数的抛出异常类型相同时,执行4个参数的方法
(4)Spring会选择签名与抛出异常最匹配的一个(同(2)所示)
示例代码:
WorkBean.java
package ch6.SimpleAOP.ExceptionAdvise;
public class WorkBean ...{
public void errorProneMethod() throws Exception...{
throw new Exception();
}
public void otherErrorProneMethod() throws IllegalArgumentException...{
throw new IllegalArgumentException();
}
}
ExceptionAdvise.java
package ch6.SimpleAOP.ExceptionAdvise;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class ExceptionAdvise implements ThrowsAdvice ...{
public void afterThrowing(Exception ex) throws Throwable...{
System.out.println("in exception advice");
}
public void afterThrowing(Method method,Object[] obj,Object target,IllegalArgumentException ex) throws Throwable...{
System.out.println("in IllegalAccessException advice");
}
}
测试代码:
package ch6.SimpleAOP.ExceptionAdvise;
import org.springframework.aop.framework.ProxyFactory;
public class TestExceptionAdvise ...{
/** *//**
* @param args
*/
public static void main(String[] args) ...{
WorkBean workBean=getWorkBean();
try ...{
workBean.errorProneMethod();
} catch (Exception e) ...{
}
try ...{
workBean.otherErrorProneMethod();
} catch (IllegalArgumentException e) ...{
}
}
public static WorkBean getWorkBean()...{
WorkBean target=new WorkBean();
ProxyFactory pf=new ProxyFactory();
pf.addAdvice(new ExceptionAdvise());
pf.setTarget(target);
return (WorkBean)pf.getProxy();
}
}
运行结果:
in exception advice
in IllegalAccessException advice