使用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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章