在Spring中异常处理机制实例测试

在Spring中异常处理机制实例测试 2009-05-31 16:44

字号:    

最近用Spring做一个项目,发现其异常处理情况与Hibernate不同,就写了个测试出来

在Spring中只有捕获RuntimeException这个异常,才能够事务回滚,还有就是异常放在哪一层效果比较好。是放在业务层,还是放在持久层

第一种异常放在Dao层:
Dao的代码:
public int saveHbzl(SysHbzl hbzl) {
 try{
  this.getHibernateTemplate().save(hbzl); 
  this.getHibernateTemplate().flush();
  this.getHibernateTemplate().clear();

 } catch (RuntimeException e) { //这个RuntimeException是一定要的
  //给维护员看的
  e.printStackTrace();
  System.out.println("测试是否出错回滚");
  System.out.println("DAO层触发saveHbzl方法异常");
   
  throw e;//能回滚
  //return 1;//不能回滚,等下到service看一下
 }
 //这里主要是想有个返回值判断。看来想多个返回值多处理是不行了
 //当然只要根据情况多个try catch还是可以返回多处理值的
 return 0;
}
在Dao层有两点,一定要捕获RuntimeException这个异常,然后再扔出。扔出给Service
这样Service就可以不用捕获异常了。
Service的代码:


而在Action中呢可以这样处理
Action的代码:
 try{
  hbzlService.saveHbzl(hbzl);
  json="{success:'true'}";
    
 }catch(Exception e){
  //给客户看的
  System.out.println("HBZL保存出错!");
  json="{success:false}";   
 }


第二种异常放在Service中:
Dao里面的代码:
  this.getHibernateTemplate().save(hbzl); 
  this.getHibernateTemplate().flush();
  this.getHibernateTemplate().clear();

Service的代码:
public int saveHbzl(SysHbzl hbzl) {
  try{
   return hbzlDao.saveHbzl(hbzl);
  }catch(RuntimeException e){
   System.out.println("在Service中的异常");
   throw e;//能回滚
   //return 1;//不能回滚,看来还是这样
  }

}
Action的代码:
 try{
  hbzlService.saveHbzl(hbzl);
  json="{success:'true'}";
    
 }catch(Exception e){
  //给客户看的
  System.out.println("HBZL保存出错!");
  json="{success:false}";   
 }

Spring XML中的配置文件是这样的

<!--====================事务代理======================= -->
     <!-- 第一个属性:transactionManager是设置事务管理器 -->
     <!-- 第二个属性:target是设置要代理的对象 -->
     <!-- 第三个属性:transactionAttributes是设置代理对象的方法的事务属性-->
     <bean id="proxyHbzlService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
         <property name="transactionManager">
             <ref bean="hibernateTransactionManager"/>
         </property>
         <property name="target">
             <ref local="hbzlService"/>
         </property>
         <property name="transactionAttributes">
             <props>
                 <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
                 <prop key="save*">PROPAGATION_REQUIRED</prop>
                 <prop key="edit*">PROPAGATION_REQUIRED</prop>
                 <prop key="del*">PROPAGATION_REQUIRED</prop>
             </props>
         </property>
     </bean>
    
最后总结:
在Spring中只有捕获RuntimeException这个异常,才能够事务回滚.判断上为try catch
在Dao层的处理比较细微,方便给维护员查询。而在Service中则不用在Dao里多次使用try catch
Service与Dao的关系是1:N.还有事务处理层一定要放在Service上
还有要记住异常有两种,一种是给客户的,一种是给维护人员看的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值