---
title: "[转]关于spring声明式事务管理异常处理的测试和小结一"
author: "daodan988"
date: "2010-08-16T13:36:40Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2010-08-16T13:40:56Z"
id: 738338
url: "https://daodan988.iteye.com/blog/738338"
---

关于spring事务管理以及异常处理的帖子，本论坛争论颇多，各有各的测试代码，也各有各的测试结果， 
不知道是spring版本的不同还是各测试的例子的不同而导致测试结果出现差异． 
本人也很想弄清楚spring是如何对Service进行事务管理的，并且还去看了一下spring框架关于事务管理几个相关类的源码，可惜由于本人功力有限，只看懂了皮毛． 
既然源代码看不懂，那么只有运用例子进行测试，虽然笨了点，不过管是白猫还是黑猫，能捉老鼠就是好猫．：） 
为引起不必要的争论，本帖子只针对本案例的测试结果进行小结，并保证此测试代码在本人的运行环境绝对正确．

开发环境： 
ＯＳ：windows 2003 Server 
Web Server: jakarta-tomcat-5.0.28 
DataBase Server: MS SQL Server 2000 (打了ＳＰ３补丁) 
IDE: Eclipse 3.2.0+MyEclipse 5.0GA

测试案例系统结构： 
web层<---->Service层<---->DAO层

web层使用struts 1.1，DAO使用的spring的JDBC，spring版本1.2

数据库中有两张表： 
student1和Student2，表结构相同：id,name,address．其中id为主键且为自增长型. 
student1表中有一条记录： 


代码
id   name        address    
1    xiaoming     wuhan    
   
student2表中记录为空  
测试情形一： 
web层捕获异常并处理，DAO层不捕获异常，Service也不捕获异常．

Service层接口：


代码
public interface StudentManagerService {    
      
    public void   bus_method();    
}  
DAO层接口 


代码
public interface StudentDAO {    
      
    public void   deleteStudent1();    
    public void   insertStudent2();    
}  
StudentDAO接口的实现： 


代码
public class StudentDAOImp extends JdbcDaoSupport implements StudentDAO{    
     //删除student1表中的id=1的记录    
     public void   deleteStudent1(){    
　　　　　JdbcTemplate jt=this.getJdbcTemplate();    
　　　　　jt.update("delete from student1 where id=1");         
　　　}    
         
     //将student1表中删除的记录插入到student2中,但是此方法实现有错，因为    
　　　//id字段设置为自增长的，所以在插入记录时我们不能指定值    
     　 public void   insertStudent2(){    
　　　　　　　JdbcTemplate jt=this.getJdbcTemplate();    
             String arg=new String;    
        arg="1";    
             arg="xiaoming";    
        arg="wuhan";    
             jt.update("insert student2(id,name,address) values(?,?,?)",arg);    
      }    
   
}   
StudentManagerService 接口的实现： 


代码
public class StudentManagerServiceImp implements StudentManagerService{    
  private StudentDAO   stdDAO;    
   
  public void setStdDAO(StudentDAO    stdDAO){    
     this.stdDAO=stdDAO;    
   }    
       
  //此方法为事务型的：删除student1中的记录成功且插入student2的记录也成功，    
　//如果insertStudent2()方法执行失败，那么deleteStudent1()方法也应该会失败    
  public void   bus_method(){    
    this.stdDAO.deleteStudent1();    
    this.stdDAO.insertStudent2();    
   }    
      
}   
web层: 
三个jsp,一个action: 
index.jsp ==>首页面．上面仅仅有一个超链接<a herf="test.do">执行</a> 
chenggong.jsp ==>Service执行成功后转向的JSP页面 
shibai.jsp　====>Service执行失败后转向的JSP页面

action实现： 


代码
public class StudentManagerAction  extends   Action{    
   
     public ActionForward execute(ActionMapping mapping, ActionForm form,    
     HttpServletRequest request, HttpServletResponse response) {    
         try{    
              WebApplicationContext appContext=WebApplicationContextUtils.    
                   getWebApplicationContext(this.getServlet().getServletContext());    
         StudentManagerService stdm=(StudentManagerService)appContext.    
                                         getBean("stdServiceManager");    
             stdm.bus_method();    
            return mapping.findForward("chenggong");    
      }    
     catch(DataAccessException e){    
         System.err.println("action execute service exception!");    
        return mapping.findForward("shibai");    
       }    
   
     }    
}  
配置文件：

web.xml 


代码
<?xml version="1.0" encoding="UTF-8"?>   
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">   
  <context-param>   
    <param-name>log4jConfigLocation</param-name>   
    <param-value>/WEB-INF/log4j.properties</param-value>   
  </context-param>   
  <context-param>   
    <param-name>contextConfigLocation</param-name>   
    <param-value>/WEB-INF/applicationContext.xml</param-value>   
  </context-param>   
  <listener>   
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   
  </listener>   
  <listener>   
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
  </listener>   
  <servlet>   
    <servlet-name>action</servlet-name>   
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>   
    <init-param>   
      <param-name>config</param-name>   
      <param-value>/WEB-INF/struts-config.xml</param-value>   
    </init-param>   
    <init-param>   
      <param-name>debug</param-name>   
      <param-value>3</param-value>   
    </init-param>   
    <init-param>   
      <param-name>detail</param-name>   
      <param-value>3</param-value>   
    </init-param>   
    <load-on-startup>0</load-on-startup>   
  </servlet>   
  <servlet-mapping>   
    <servlet-name>action</servlet-name>   
    <url-pattern>*.do</url-pattern>   
  </servlet-mapping>   
</web-app>  
sturts-config.xml 


代码
<struts-config>   
  <action-mappings >   
    <action  input="/index.jsp"  path="/test"  type="test.StudentManagerAction   >   
      <forward name="chenggong" path="/chenggong.jsp" />   
      <forward name="shibai" path="/shibai.jsp" />   
    </action>   
  </action-mappings>   
  <message-resources parameter="test.ApplicationResources" />   
</struts-config>  
applicationContext.xml 


代码
<?xml version="1.0" encoding="UTF-8"?>   
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">   
<beans>   
    <bean id="dataSource"   
      class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >   
      <property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"></property>   
      <property name="url" value="jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=test"></property>   
       <property name="username" value="sa"></property>   
       <property name="password" value="sa"></property>   
    </bean>   
        
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
        <property name="dataSource" ref="dataSource"/>   
     </bean>   
            
    <bean id="baseTxProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"  lazy-init="true">   
        <property name="transactionManager">   
        <ref bean="transactionManager" />   
         </property>   
         <property name="transactionAttributes">   
         <props>   
             <prop key="*">PROPAGATION_REQUIRED</prop>   
        </props>   
         </property>   
    </bean>   
   
    <bean id="stdServiceManager"  parent="baseTxProxy" >   
        <property name="target">   
             <bean class="test.StudentManagerServiceImp">        
                       <property name="stdDAO">   
　　　　　　　　　             <ref bean="stdDAO"/>   
                       </property>        
                  </bean>    
        </property>    
    </bean>   
   
    <bean id="stdDAO" class="test.StudentDAOImp">   
       <property name="dataSource" ref="dataSource"/>   
    </bean>   
</beans>  
运行程序：启动服务器，并部署．进入index.jsp页面，点击"执行"超链接"---->页面跳向shibai.jsp 
查看控制台：打印有：action execute service exception! 
查看数据库：　student1表中的 记录仍然存在，student2表仍然为空． 
<span style="color:red">小结：如果DAO层和Service不捕获异常而在web层捕获异常，web成功捕获异常，spring事务管理成功！</span>