Spring AOP在处理异常方面有着显著优势,下面实例说明。
定义LogicService
</pre><pre name="code" class="java">package com.jike.spring.chapter10.aop.advice;
public class LogicService {
public void saveData(){
// To do sth
throw new RuntimeException("运行异常。");
}
public void updateData(){
// Update
throw new RuntimeException("运行异常。");
}
}
package com.jike.spring.chapter10.aop.advice;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class LogicServiceInterceptor implements ThrowsAdvice {
public void afterThrowing(Method method, Object[] args, Object target,
Exception ex) throws Throwable {
System.out.println("-----------");
System.out.println("method:" + method.getName());
System.out.println("抛出异常:" + ex.getMessage());
System.out.println("成功回滚事务。");
}
}
配置文件
<bean id="forumServiceTarget" class="com.jike.spring.chapter10.aop.advice.LogicService" />
<bean id="transactionManager" class="com.jike.spring.chapter10.aop.advice.LogicServiceInterceptor" />
<bean id="forumService" class="org.springframework.aop.framework.ProxyFactoryBean"
p:interceptorNames="transactionManager" p:target-ref="forumServiceTarget"
p:proxyTargetClass="true" />
测试类
package com.jike.spring.chapter10.aop.advice;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestExceptionAop {
@Test
public void testException() {
String configPath = "conf/conf-advice.xml";
ApplicationContext app = new ClassPathXmlApplicationContext(configPath);
LogicService logic = (LogicService) app.getBean("forumService");
try {
logic.saveData();
} catch (Exception e) {
System.out.println("handle");
}
}
}
运行结果
-----------
method:saveData
抛出异常:运行异常。
成功回滚事务。
handle