Spring:中的事務控制

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置spring內置數據源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/day01"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    <!--spring中基於xml的聲明式事務控制配置步驟
        配置事務管理器
        配置事務通知
            導入事務的約束 tx名稱空間約束,同時也需要aop的
            使用tx:advice標籤配置事務通知
                屬性
                    id 給事務唯一通知
                    transaction-manager 給事務通知一個事務管理器用
        配置aop通用切入點表達式
     建立事務通知和切入點表達式對應關係
     配置事務屬性
            在事務的通知tx:advice標籤內部
    -->
    <!--配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--配置事務屬性
            isolation 用於指定隔離級別 默認是default 表示使用數據庫的隔離級別
            propagation 指定事務的傳播行爲 默認是required 表示一定有事務 增刪改的選擇  查詢方法可以選擇 supports
            read-only 指定事務是否只讀 只有查詢方法才能設置爲true 默認是false
            timeout 指定事務的超時時間 默認是-1 表示永不超時 如果指定了數據 單位爲秒
            rollback-for 用於指定一個異常 當產生異常 事務回滾 產生其他異常 事務不回滾 沒有默認值 任何異常都回滾
            no-rollback-for 指定一個異常 當產生異常時 事務不回滾 產生其他異常時 事務回滾 沒有默認值 表示任何異常都回滾
        -->
        <tx:attributes>
            <tx:method name="accountService" propagation="REQUIRED" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!--配置aop-->
    <aop:config>
        <!--配置切入點表達式-->
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
        <!--建立切入點表達式和事務通知的對應關係-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章