异常通知类
public class MyThrowAdvice {
public void MyThrow(Exception e) {
System.out.println("throw Exception"+e.getMessage());
}
}
Demo类
在Demo1方法中写了个5/0,让它报异常
public class Demo {
public void Demo1(){
int i=5/0;
System.out.println("demo1");
}
public void Demo2(){
System.out.println("demo2");
}
public void Demo3(){
System.out.println("demo3");
}
}
applicationContext.xml部分代码
- 异常只能用aspectJ方式实现
- 需要在aspect标签里边写
- 和schema-based一样,有切点标签、切点标签的类、通知标签、然后ref引入通知标签的bean
<bean id="mythrow" class="cn.wit.advice.MyThrowAdvice"> </bean>
<aop:config>
<aop:aspect ref="mythrow">
<aop:pointcut expression="execution(* cn.wit.test.Demo.Demo1())" id="mypoint"/>
<aop:after-throwing method="MyThrow" pointcut-ref="mypoint" throwing="e"/>
</aop:aspect>
</aop:config>
<bean id="demo" class="cn.wit.test.Demo"></bean>
测试
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Demo demo = ac.getBean("demo",Demo.class);
try {
demo.Demo1();
} catch (Exception e) {
}
}
}