spring+springMVC中使用@Transcational方式管理事務的必須要配的東西。

劍握在手發表於2015-09-19

spring中管理事務的配置方式除了@Transcational還有使用aop等,本文介紹@Transcational方式。

 

關於這兩種方式的選擇:

aop方式適合需要支援事務的方法或類較多,且方法和類名命名有規則可循的場景,aop方式耦合性低一些。

註解方式更靈活一些,但是耦合性較高,每個需要事務的地方都要新增該註解。

 

一、spring中一定要記得載入所有需要的bean

如果使用註解方式的話一定要記得掃描註解,下邊的例子表示掃描xxx.xxx下所有檔案(包含每一級子資料夾)中除了@Controller以外的所有註解。

<context:component-scan base-package="xxx.xxx">
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

二、而springmvc中則只掃描controller

<context:component-scan base-package="xxx.xxx" use-default-filters="false" >
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

既然是隻掃描,那麼預設掃描的那些東西都要去掉。總之如果使用context:include-filter(注意上邊兩段寫的分別是include和exclude),則一定不要忘記use-default-filters="false"。

 

三、spring中其它要配的除了資料來源外必須還有這些:

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 使用annotation註解方式配置事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"  />
transactionManager中的dataSource是告訴事務管理器,呼叫哪個資料庫的commit和rollback

tx:annotation-driven則是為所有已經載入進spring的(步驟一 中 的掃描就是載入過程)
且有@Transcational註解的bean交給transaction-manager中所寫的事務管理器來管理事務。

如果想指定用哪個事務管理器就可以在註解中寫了,例如@Transactional("transactionManager1")

相關文章