现在的位置: 首页 > 综合 > 正文

基于Annotation的Spring AOP: @AfterThrowing

2013年10月14日 ⁄ 综合 ⁄ 共 2409字 ⁄ 字号 评论关闭

@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,导致程序终止。

抱歉!评论已关闭.