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


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")
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM