使用SpringAOP 处理异常

    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("运行异常。");
	}
}



   定义LogicServiceInterceptor


   

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值