正如题目所说,@afterthrowing是对于java异常的处理,但是你会说Java本身也有异常机制啊 error throwable exception runtimexception 并且也有一系列的自定义异常 也有对于异常的描述 譬如:假如e 是异常对象,我们可以使用e.getmessage()方法对异常进行描述.
但是@afterThrowing是aop形式的异常描述,是在主类文件外部来对主类文件异常的描述,也就是说@afterThrowing异常增强是来自于文件外部的.
需求:我要在两个异常类中,一个使用java处理机制,一个使用aop异常处理机制
1.代码说明真相
主类component
package test;import java.io.FileInputStream;import org.sPRingframework.stereotype.Component;@Componentpublic class component { public String one(String name) { try { System.out.println("one方法开始被执行"); new FileInputStream("bean.xml"); } catch (Exception e) { System.out.println("目标类的异常处理"+e.getMessage()); e.printStackTrace(); } return name+"hello,spring aop"; } public void sum1() { int i=5/0; System.out.println("divide执行完成"); } }这里设置了两个异常 :one 和 sum1 ,前者使用java的异常处理机制 后者什么也没有做
切面类
package test;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Aspect; //定义了一个切面(切面的意思是:业务流程运行的某个特定步骤,也就是应用运行过程的关注点 ,关注点可能横切多个对象,所以也常常被称为横切关注点)@Aspect public class aspect { @AfterThrowing(pointcut="execution(* test.*.*(..))",throwing="a")//定义一个切点,切点指示符:修饰符为任意的 test包下所有的类(然后在这个范围内寻找被@compenet类注释的java类) public void doaction(Throwable a) { System.out.println("目标方法中抛出的异常:"+a); 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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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="test">//自动找出test包下所有过的类<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
// 过滤器类型:注释 表达式: org.aspectj.lang.annotation.Aspect 此处的过滤器类型有四种:annotation,assignable,regex, 当符合这些 过滤器类型,将会被当做bean类处理(即使该普通的java类没有使用注解,这就是aop迷人的地方了)
</context:component-scan> <aop:aspectj-autoproxy/>//aspectj的自定代理</beans>运行类
package test;import org.springframework.context.applicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class function { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml"); component co=ac.getBean(component.class); co.one("xxx"); co.sum1(); }}
结果图
总结:@afterthrowing更加灵活,而且对于主类文件的污染较小,是一个很方便的方法
@afterthrowing捕抓异常过程
1.主类发生异常 ;2.切面的@afterthrowing中throwing捕获到将其传到被它修饰的带参构造器中;3.切面类的构造器将错误信息打印出来
新闻热点
疑难解答