AOP-通知-异常通知
顾名思义,目标方法发生异常植入的切面
异常通知类需要实现ThrowsAdvice
接口,你会发现ThrowsAdvice
没有需要实现的方法
在源码中有猫腻
* <pre class="code">public void afterThrowing(Exception ex)</pre>
* <pre class="code">public void afterThrowing(RemoteException)</pre>
* <pre class="code">public void afterThrowing(Method method, Object[] args, Object target, Exception ex)</pre>
* <pre class="code">public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)</pre>
*
这当中有四个方法可以实现,下面我实现第一个
接口
package com.hk.spring.aop04;
public interface SomeService {
public void doFirst();
public void doSecond();
}
接口实现
package com.hk.spring.aop04;
public class SomeServiceImpl implements SomeService {
@Override
public void doFirst() {
System.out.println("主业务doFirst");
//搞个异常出来
int a = 4;
int b = 0;
a = a / b;
}
@Override
public void doSecond() {
System.out.println("主业务doSecond");
}
}
异常通知
package com.hk.spring.aop04;
import org.springframework.aop.ThrowsAdvice;
/**
* 异常通知
* @author 浪丶荡
*
*/
public class MyThrowsAdvice implements ThrowsAdvice {
//在目标方法发异常时执行
public void afterThrowing(Exception ex){
System.out.println("执行异常通知方法:发生的异常是——"+ex.getMessage());
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean name = "someService" class="com.hk.spring.aop04.SomeServiceImpl"></bean>
<!-- 注册通知 -->
<bean name = "myThrowsAdvice" class="com.hk.spring.aop04.MyThrowsAdvice"></bean>
<!-- 生成代理对象 -->
<bean name = "serviceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 配置代理对象的目标对象属性 (类加载器)-->
<property name="target" ref="someService"/>
<!-- 或者这样配置
<property name="targetName" value="someService"/>
-->
<!-- 配置切面 (方法)-->
<property name="interceptorNames" value="myThrowsAdvice"/>
<!-- 接口通过private boolean autodetectInterfaces = true可以被找到 -->
</bean>
</beans>
测试
package com.hk.spring.aop04;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
@Test
public void test1(){
String resoure = "com/hk/spring/aop04/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resoure);
SomeService someService = (SomeService) ac.getBean("serviceProxy");
someService.doFirst();
someService.doSecond();
}
}
结果
主业务doFirst
执行异常通知方法:发生的异常是——/ by zero