Spring 声明式事务 一步登天

来源:互联网 发布:怎么链接淘宝店铺宝贝 编辑:程序博客网 时间:2024/05/16 16:00

利用Spring aop的自动代理,Spring  管理事务超级简单

打开Spring 配置文件 applicationContext.xml,加入如下代码

 <bean id="autoProxy"
  class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
 </bean>


 <bean id="transactionAdvisor"
  class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
  <constructor-arg>
   <ref bean="transactionInterceptor" />
  </constructor-arg>
 </bean>


 <bean id="transactionInterceptor"
  class="org.springframework.transaction.interceptor.TransactionInterceptor">
  <property name="transactionManager">
   <ref bean="transactionManager" />
  </property>
  <property name="transactionAttributeSource">
   <ref bean="transactionAttributeSource" />
  </property>
 </bean>


 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>


 <bean id="transactionAttributeSource"
  class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource">
  <property name="properties">
   <props>
    <prop key="get*">PROPAGATION_SUPPORTS,readOnly</prop>
    <prop key="find*">PROPAGATION_SUPPORTS,readOnly</prop>
    <prop key="load*">PROPAGATION_SUPPORTS,readOnly</prop> 
      <prop key="search*">PROPAGATION_SUPPORTS,readOnly</prop> 
      <prop key="save*">PROPAGATION_REQUIRES_NEW</prop> 
      <prop key="add*">PROPAGATION_REQUIRES_NEW</prop> 
      <prop key="update*">PROPAGATION_REQUIRES_NEW</prop> 
       <prop key="remove*">PROPAGATION_REQUIRES_NEW</prop> 
        <prop key="delete*">PROPAGATION_REQUIRES_NEW</prop>

   </props>
  </property>
 </bean>

 

好了,一切都搞定了,注意红色部分,所有get,find,load...等开头的方法,都会自动套用对应的事务管理方案,你可以增加红色部分,适用新的方法。

实践建议:j2ee应用程序,一般有试图层,控制层,service层,dao层,事务控制应该在service完成,而自动代理,会代理系统所有类指定名称方法!所以,建议把所有service层方法以M结尾,然后设置<prop key="delete*M">PROPAGATION_REQUIRES_NEW</prop> ,

 
原创粉丝点击