一、配置異常通知的步驟 (Aspectj方式)
1、只有當切點報異常才能觸發異常通知
2、在spring中有Aspectj 方式提供了異常通知方法
2.1 如果希望通過 schema-base 實現需要按照特定的要求自己編寫方法
3、實現步驟:
3.1 新建類,在類中寫任意名稱的方法
public class myExcetion { public void myexcetion(Exception e1){ System.out.println("執行異常,tain"+e1.getMessage()); } }
3.2 在spring配置文件中配置
3.2.1 <aop:aspect ref="">:ref= 表示在哪個類中
3.2.2 <aop:xxxx> 什么標簽表示什么通知
3.2.3 method:表示當觸發這個通知時,調用哪個方法
<?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="myexcetion" class="com.bjsxt.myExcetion.myexcetion"></bean> <aop:config> <aop:aspect ref="myexcetion"> <aop:pointcut expression="execution(* com.bjsxt.test.Test.demo1())" id="mypoint"/> <aop:after-throwing method="myExcetion" pointcut-ref="mypoint" throwing="e1"/> throwing 表示異常處理的方法的參數名 (可以不再異常通知中聲明異常對象) </aop:aspect> </aop:config> <bean id="test" class="com.bjsxt.test.Test"></bean> </beans>
二、使用Schema-base 實現異常
1、新建一個類實現ThrowsAdvice接口,且必須使用afterThrowing這個方法名。。
1.1有兩種參數方式
必須有 1個 或 4個參數
1.2 異常類型要與切點報的異常類型一致,
public class Mythrow implements ThrowsAdvice{ // public void afterThrowing(Exception ex) throws Throwable { // System.out.println("執行異常通知11111"); //} public void afterThrowing(Method m, Object[] args, Object target, Exception ex) { System.out.println("執行異常通知2222"); } }
2、在applicationContext.xml中配置
<?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="com.bjsxt.advice.Mythrow"></bean> <bean id="demo" class="com.bjsxt.test.Demo"></bean> <aop:config> <aop:pointcut expression="execution(* com.bjsxt.test.Demo.demo1())" id="mypoint"/> <aop:advisor advice-ref="mythrow" pointcut-ref="mypoint"/> </aop:config> </beans>