1. 程式人生 > 其它 >AOP-schema-based實現異常通知

AOP-schema-based實現異常通知

技術標籤:ssmspringaop

application.xml

  • 切點標籤、切點物件
  • 通知標籤、通知物件
  • aspectJ方式是自己定義方法,通知標籤只指明瞭通知類中的方法名,然後還要在aspect標籤上寫通知類的類名
  • schema-based是固定的方法,異常通知類中的方法名必須為afterThrowing,所以通知標籤中指明通知類即可
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<bean id="mythrow" class="cn.wit.advice.MyThrow"></bean> <aop:config> <aop:pointcut expression="execution(* cn.wit.test.Demo.Demo1())" id="mypoint"/> <aop:advisor advice-ref="mythrow" pointcut-ref
="mypoint"/>
</aop:config> <bean id="demo" class="cn.wit.test.Demo"></bean> </beans>

異常通知類

方法名必須為afterThrowing

public class MyThrow implements ThrowsAdvice{
	public void afterThrowing(Exception ex) throws Throwable{
		System.out.println("異常通知");
	}
	
}

Demo類

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");
	}
	
}

測試

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) {
		} 
	}
}