Spring的事務復原,當且僅當捕獲到RuntimeException類型異常時,才會復原,對普通Exception異常無效。
以下是我Service層捕獲異常,并抛出RuntimeException異常到Action層:
[java] view plain copy
- @Override
- public void lock(String id) throws RuntimeException {
- try {
- this.loginUserDao.lock(id);
- LoginUser user = this.loginUserDao.findById(id);
- user.setSex("捕捉到異常後,抛出RuntimeException類型的異常");
- this.loginUserDao.save(user);
- } catch (Exception e) {
- // 捕捉到異常後,抛出RuntimeException類型的異常。
- // spring 事務隻在捕足到RuntimeException異常時,才會復原,對Exception無效
- throw new RuntimeException(e.getMessage());
- }
- }
spring中事務管理配置:
[html] view plain copy
- <!-- 為sessionFactory定義事務管理器 -->
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory">
- <ref local="sessionFactory" />
- </property>
- </bean>
- <!-- 定義事務攔截器 -->
- <bean id="transactionInterceptor"
- class="org.springframework.transaction.interceptor.TransactionInterceptor">
- <!-- 為事務攔截器注入一個事務管理器 -->
- <property name="transactionManager" ref="transactionManager" />
- <property name="transactionAttributes">
- <!-- 定義事務傳播屬性 PROPAGATION_REQUIRED:表示如果事務不存在,則建立一個新事務,如果存在,則加入到該事務。 -->
- <props>
- <prop key="save*">PROPAGATION_REQUIRED</prop>
- <prop key="add*">PROPAGATION_REQUIRED</prop>
- <prop key="delete*">PROPAGATION_REQUIRED</prop>
- <prop key="update*">PROPAGATION_REQUIRED</prop>
- <prop key="lock*">PROPAGATION_REQUIRED</prop>
- <prop key="unLock*">PROPAGATION_REQUIRED</prop>
- <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
- <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>
- <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
- <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
- </props>
- </property>
- </bean>
- <!-- 定義攔截器要攔截的bean -->
- <bean id="autoProxy"
- class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
- <property name="beanNames">
- <list>
- <!-- 攔截所有名字以Service結尾的bean進行代理 -->
- <value>*Service</value>
- </list>
- </property>
- <property name="interceptorNames">
- <list>
- <value>transactionInterceptor</value>
- </list>
- </property>
- </bean>