在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上
还有要记住异常有两种,一种是给客户的,一种是给维护人员看的
本文探讨了Spring框架中的异常处理机制,重点讲解如何通过捕获RuntimeException实现事务回滚,并对比了在DAO层和服务层处理异常的不同效果。
1114

被折叠的 条评论
为什么被折叠?



