1:Spring 的异常通知是在方法抛出异常之后将通知切入。
需要注意的是异常通知只是当方法抛出异常时对抛出异常的情况进行操作,它不会捕获原方法抛出的异常.
2: Spring 提供了ThrowAdvice 接口来实现异常通知。ThrowAdvice 接口只是一个标示接口,它没有任何的方法,但是在使用时我们需要实现afterThrowing 方法来实现通知的具体内容。通过异常参数类型的定义,通知织入相的对应的异常之中,即当afterThrowing 的参数指定为NumberFormatException 异常时,当原方法抛出了该异常,通知被自动的执行。
我们可以根据抛出的异常信息写异常日志,这样就能很清楚的知道那个人在什么时候的操作有异常.
例子如下:
1)异常通知
package com.zking.springproxy;
import org.springframework.aop.ThrowsAdvice;
public class Throw implements ThrowsAdvice {
public void afterThrowing () {
System.out.println("抛出异常");
throw new NumberFormatException();
}
}
xml文件
<!-- 设置目标 -->
<bean id="z" class="com.zking.springproxy.zq"></bean>
<!-- 代理配置 -->
<bean id="myproxy"
class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 引用目标 -->
<property name="target" ref="z"></property>
<property name="proxyInterfaces">
<list>
<value>com.zking.springproxy.IPerson</value>
</list>
</property>
<!-- 引用通知 -->
<property name="interceptorNames">
<list>
<idref bean="Mythrow" />
</list>
</property>
</bean>
<bean id="Mythrow" class="com.zking.springproxy.Throw"></bean>
test测试
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
IPerson ip=(IPerson) applicationContext.getBean("myproxy");
//得到代理 代理怎么调用方法 最终用接口执行
ip.sleep();
ip.Personadd();
}
异常通知 你可以自己设置什么错误时会抛出异常 比如我定义的是报空指针的时候抛出异常 它就会在你报空指针时候抛出.
//异常通知
@AfterThrowing(value="execution(* com.at.aop.ArithmeticCalculator.*(..))",throwing="ex")
public void afterThrowing(JoinPoint joinPoint,Exception ex){
String methodName = joinPoint.getSignature().getName();
System.out.println("异常通知方法 "+methodName+" 发生的异常为 "+ex);
}
@AfterThrowing注解表示这个方法是用来作为异常通知,也就是在它签名中所标识的具体方法调用并出现异常之后才会进入这个方法
并且要在方法参数里面添加一个"Exception ex",这个变量名要与刚才throwing所匹配的名字一致!
value属性表示所装配的类和方法
throwing表示返回的异常对象