天天看點

Spring對聲明式事務的支援

Spring對聲明式事務的支援

Spring的事務控制首先明确

一般我們對資料庫資料進行管理的時候,很多時候我們都需要對資料進行控制,事務的控制很關鍵,這些代碼之間互相的很多都是重複的代碼,不符合我們程式設計的思想,我們希望能夠把這些相同的代碼給提取出來,實作代碼的可重複性,衆所周知,我們處理業務邏輯的時候一般都牽扯到事務的需求,在這裡我們就以轉賬的業務為例,JavaEE體系進行分層開發,事務處理為于業務層,Spring提供了分層設計業務層的事務處了解決方案,spirng的事務控制都是基于aop的,它即可以通過程式設計的方式來實作,也可以通過配置的方式來實作,我們這裡重點是學習通過配置的方式來實作

Spring的基于xml的聲明式事務的執行流程

1.配置事務管理器

2.配置事務的通知

此時事先需要導入事務的限制,tx的名稱和空間,同時還需要aop的注解,使用tx:advice标簽配置事務通知.屬性id給事務起了一個唯一的辨別,transaction-manager:給事務通知提供一個事務管理器引用

3.配置AOP的切入點表達式

4.建立通知和切入點的表達式

5.配置事務的屬性

<!--配置事務管理器(事務的切面類)-->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"></property>
     </bean>

     <!--配置事物的通知 transaction-manager配置是那個事務的特性-->
     <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="*" propagation="REQUIRED" read-only="false"/>
               <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
          </tx:attributes>
     </tx:advice>

     <!--配置AOP-->
     <aop:config>
          <!--配置切入點表達式-->
          <aop:pointcut id="pt1" expression="execution(* cn.ujiuye.service.impl.*.*(..))"/>
          <!--建立切入點表達式和事務通知的對應的關系-->
          <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
     </aop:config>
           

Spring的基于xml的聲明式事務的代碼展現

1.配置bean.xml配置檔案的書寫,加載配置檔案對應的資訊

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

     <!--配置業務層-->
     <bean id="accountService" class="cn.ujiuye.service.impl.AccountServiceImpl">
          <property name="accountDao" ref="accountDao"></property>
     </bean>

     <!--配置賬号的持久層-->
     <bean id="accountDao" class="cn.ujiuye.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
     </bean>

     <!--配置資料源,配置spring中的資料源-->
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
          <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
          <property name="username" value="root"></property>
          <property name="password" value="123"></property>
     </bean>

     <!--spring中基于xml的聲明式事務控制的配置過程
         1.配置事物管理器
         2.配置事務的通知
             此時事先導入事務的限制 tx的名稱和空間,同時還需要aop的
             使用tx:advice标簽配置事務通知
                屬性:
                    id:給事務起一個唯一标志
                    transaction-manager:給事務通知提供一個事務管理器引用
         3.配置AOP中的通用切入點表達式
         4.建立通知和切入點的表達式的對應關系
         5.配置事務的屬性

         通知管理器在準守事務的通知的配置後,作用在切點上,完成事務的特點

     -->
     <!--配置事務管理器(事務的切面類)-->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"></property>
     </bean>

     <!--配置事物的通知 transaction-manager配置是那個事務的特性-->
     <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="*" propagation="REQUIRED" read-only="false"/>
               <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
          </tx:attributes>
     </tx:advice>

     <!--配置AOP-->
     <aop:config>
          <!--配置切入點表達式-->
          <aop:pointcut id="pt1" expression="execution(* cn.ujiuye.service.impl.*.*(..))"/>
          <!--建立切入點表達式和事務通知的對應的關系-->
          <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
     </aop:config>
</beans>
           

2.定義其實作的過程

package cn.ujiuye.service.impl;

import cn.ujiuye.dao.IAccountDao;
import cn.ujiuye.domain.Account;
import cn.ujiuye.service.IAccountService;


import java.util.List;

/**
 * @author liugang
 * @date 2019/10/5
 * 賬号的業務邏輯層的實作類
 * 事務的業務邏輯也是在這層來控制的
 */
public class AccountServiceImpl implements IAccountService {

    /*使用的是set注入的方法來實作注入accountDao資料*/
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao){
        this.accountDao = accountDao;
    }

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);

    }


    public void transfer(String sourceName, String targetName, Float money) {


        System.out.println("transfer....");
        //2.1根據名稱查詢轉出賬戶
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根據名稱查詢轉入賬戶
        Account target = accountDao.findAccountByName(targetName);
        //2.3轉出賬戶減錢
        source.setMoney(source.getMoney()-money);
        //2.4轉入賬戶加錢
        target.setMoney(target.getMoney()+money);
        //2.5更新轉出賬戶
        accountDao.updateAccount(source);

        int i=1/0;

        //2.6更新轉入賬戶
        accountDao.updateAccount(target);
    }
}

           

3.書寫測試類

package cn.ujiuye.test;

import cn.ujiuye.domain.Account;
import cn.ujiuye.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * @author liugang
 * @date 2019/10/5
 * 使用Junit單元測試,測試我們的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceImplTest {

    @Autowired
    private IAccountService as;
    @Test
    public void testTransfer(){
        as.transfer("aaa","bbb",100f);
    }

}

           

繼續閱讀