1 新建类,实现ThrowsAdvice接口
必须自己写方法,必须叫做afterThrowing
用两种参数方式,(1个参数或4参)
public class MyThrow implements ThrowsAdvice{
//方法1
public void afterThrowing(Exception ex) throws Throwable{
System.out.println("执行异常通过-schema-base");
}
//方法2
// public void afterThrowing(Method m, Object[] args, Object target, Exception ex) {
// System.out.println("执行异常通知");
// }
}
xml
<bean id="demo" class="com.lee.service.DemoService"/>
<bean id="mythrow" class="com.lee.advice.MyThrow"/>
<aop:config>
<aop:pointcut expression="execution(* com.lee.service.*.*(..))" id="mypoint"/>
<aop:advisor advice-ref="mythrow" pointcut-ref="mypoint"/>
</aop:config>
切点
public class DemoService {
public void demoMethod() {
int i = 5/0;
System.out.println("DemoMethod execute");
}
}
测试方法
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
DemoService ds = (DemoService) ac.getBean("demo");
ds.demoMethod();
}
}
输出
Exception in thread "main" 执行异常通过-schema-base
java.lang.ArithmeticException: / by zero