1. 程式人生 > >基於Annotation的Spring AOP: @AfterThrowing

基於Annotation的Spring AOP: @AfterThrowing

@AfterThrowing 主要用於處理程式中未處理的異常。

使用@AfterThrowing 時可指定如下兩個屬性:

① pointcut / value : 用於指定該切入點對應的切入表示式。

throwing : 指定一個返回值形參名,增強處理定義的方法可通過該形參名來訪問目標方法中所丟擲的異常物件。

Person.java :

public interface Person {
	public String sayHello(String name);
	public void divide();
}
Chinese.java :
@Component
public class Chinese implements Person {

	@Override
	public void divide() {
		int a=5/0;
		System.out.println("divide執行完成!");
	}

	@Override
	public String sayHello(String name) {
		try {
			System.out.println("sayHello方法開始被執行...");
			new FileInputStream("a.txt");
		} catch (FileNotFoundException e) {
			System.out.println("目標類的異常處理"+e.getMessage());
		}
		return name+" Hello,Spring AOP";
	}

	
}
AfterThrowingAdviceTest.java :
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

/**
 * 定義一個切面
 * @author Administrator
 *
 */
@Aspect
public class AfterThrowingAdviceTest {
	
	@AfterThrowing(throwing="ex",pointcut="execution(* com.bean.*.*(..))")
	public void doRecoveryActions(Throwable ex){
		System.out.println("目標方法中丟擲的異常:"+ex);
		System.out.println("模擬丟擲異常後的增強處理...");
	}
}
bean.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:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context 
                http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    
    
    <context:component-scan base-package="com.bean">
        <context:include-filter type="annotation" 
                 expression="org.aspectj.lang.annotation.Aspect"/>
    </context:component-scan>
    
   <aop:aspectj-autoproxy/>
    
 </beans>
Test.java :
public class Test {
	public static void main(String[] args) {
		
		ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
		Person p=(Person) ctx.getBean("chinese");
		System.out.println(p.sayHello("張三"));
		p.divide();
	}
}
執行控制檯輸出:


上面程式中的sayHello方法和divide兩個方法都會丟擲異常,但sayHello方法中的異常將由該方法顯式捕捉,所以Spring AOP不會處理該異常;而divide方法將丟擲ArithmeticException異常,且該異常沒有被任何程式所處理,故Spring AOP會對該異常進行處理。

catch捕捉 意味著完全處理該異常,如果catch塊中沒有重新丟擲新異常,則該方法可以正常結束;而 AfterThrowing 雖然處理了該異常,但他不能完全處理該異常,該異常依然會傳播到上一級呼叫者,本例中傳播到JVM,導致程式終止。