Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring 基於 AOP 的事務管理實戰

先談事務本身

事務是一串被視為單一工作單位的動作:只要有任何一步失敗,整個流程就退回最初的狀態,彷彿什麼都沒發生過。最經典的例子就是轉帳——扣款與入帳必須成對成立,只完成一半只會製造錯誤與損失。事務管理技術正是用來避免這類情形,確保資料的完整與一致,因此在企業級開發中幾乎是標配。

事務的四個特性簡稱 ACID:

  1. 原子性(Atomicity):事務是原子的,所有動作要嘛全部完成,要嘛完全不執行。
  2. 一致性(Consistency):事務結束後(不論成敗),系統所建模的業務必須處於一致狀態。
  3. 隔離性(Isolation):多個事務可能同時處理相同資料,彼此必須隔離,避免資料損壞。
  4. 持久性(Durability):事務一旦完成,即便發生系統錯誤,結果也不受影響,通常會寫入持久化儲存媒體。

Spring 的事務是建立於面向切面程式設計(AOP)之上。事務屬性包含傳播行為、隔離級別、回滾規則、唯讀與超時,而 Spring 事務管理有三個核心介面:

  • TransactionDefinition:事務描述物件,提供取得事務相關資訊的方法。
  • PlatformTransactionManager:平台事務管理器,負責實際管理事務。
  • TransactionStatus:描述某一時間點上事務的狀態。

為什麼需要 AOP

物件導向擅長描述縱向關係,卻不適合表達橫向關注點——日誌、權限、異常處理這類邏輯往往散落在各處,與核心業務無關卻反覆出現,這種現象稱為橫切。AOP 就是一種橫切技術:把影響多個類的共同行為抽出成可重用單元(切面),从而降低重複程式碼、鬆散模組耦合,也讓後續維護更輕鬆。

幾個常見術語:

  1. 連接點(Joinpoint):被攔截的點,可以是方法、欄位或構造器。
  2. 切入點(Pointcut):決定要攔截哪些連接點。
  3. 通知(Advice):攔截之後要執行的程式碼,分為前置、後置、異常、最終、環繞五種。
  4. 目標(Target):被代理的目標物件。
  5. 織入(Weaving):把增強邏輯套用到目標、生成代理物件的過程。
  6. 切面(Aspect):切入點與通知的集合。

實作:轉帳案例

用 MySQL 建立名為 User 的資料庫,裡面放兩張表:用戶資訊表 t_user 與存款表 account,然後實作 A 向 B 轉帳;一旦中途失敗,資料必須自動回到轉帳前的狀態。

專案中的類別:

// 用戶類
public class User {
    private int userID;
    private String userName;
    private String password;
    // getter / setter 省略
}

// 用戶工廠
public class UserFactory {
    public User createUser(String name, int id, String password) {
        User user = new User();
        user.setUserName(name);
        user.setUserID(id);
        user.setPassword(password);
        return user;
    }
}
// 存款訪問介面與實作
public interface AccountDao {
    public void addAccount(int id, double account);
    public void inAccount(int id, double account);
    public void outAccount(int id, double account);
}

public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbc) {
        this.jdbcTemplate = jdbc;
    }

    @Override
    public void addAccount(int id, double account) {
        this.jdbcTemplate.execute("insert into account values(" + id + "," + account + ")");
    }

    @Override
    public void inAccount(int id, double account) {
        this.jdbcTemplate.update("update account set account=account+? where userid=?", account, id);
    }

    @Override
    public void outAccount(int id, double account) {
        this.jdbcTemplate.update("update account set account=account-? where userid=?", account, id);
    }
}

服務層刻意製造一個異常,用來驗證回滾:

public interface AccountService {
    // 從 outUser 轉出 account 金額給 inUser
    public void transfer(User outUser, User inUser, double account);
}

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

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

    @Override
    public void transfer(User outUser, User inUser, double account) {
        this.accountDao.outAccount(outUser.getUserID(), account);
        int i = 1 / 0;   // 模擬程式異常,導致 inAccount 無法執行
        this.accountDao.inAccount(inUser.getUserID(), account);
    }
}

關鍵在配置檔:加上事務管理器、tx:advice 通知與 aop 切面,讓 Spring 自動為目標建立代理。

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

    <!-- 資料源(此處用 c3p0 連線池) -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost/User"/>
        <property name="user" value="root"/>
        <property name="password" value="123"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="createTables" class="com.jdbc.CreateTables">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="userDao" class="com.jdbc.UserDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="accountDao" class="com.jdbc.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="accountService" class="com.jdbc.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!-- 事務管理器,依賴資料源 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 通知:name 為方法名,* 代表全部;propagation 傳播行為;isolation 隔離級別 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!-- 切面:把切入點與通知整合起來 -->
    <aop:config>
        <aop:pointcut id="txPointCut"
            expression="execution(* com.jdbc.AccountServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

啟動 MySQL 並執行專案後,主控台會在 int i = 1 / 0 處拋出異常;此時轉出方的存款在記憶體中雖已變動,但查詢 account 表會發現金額仍是原值,A 的餘額並沒有減少——這就是事務回滾發揮了作用。

再補一刀:用 AOP 加日誌

為了把 AOP 講得更透徹,我們在轉帳前後插入日誌:

public class LogHandler {
    // 切入點執行之前
    public void LogBefore() {
        System.out.println("轉帳開始時間:" + System.currentTimeMillis());
    }
    // 切入點執行之後
    public void LogAfter() {
        System.out.println("轉帳結束時間:" + System.currentTimeMillis());
    }
}
<!-- 配置日誌類 -->
<bean id="logHandler" class="com.jdbc.LogHandler"/>
<aop:config>
    <!-- order 表示多個橫切關注點的順序 -->
    <aop:aspect id="log" ref="logHandler" order="1">
        <aop:pointcut id="logTime"
            expression="execution(* com.jdbc.AccountServiceImpl.transfer(..))"/>
        <aop:before method="LogBefore" pointcut-ref="logTime"/>
        <aop:after method="LogAfter" pointcut-ref="logTime"/>
    </aop:aspect>
</aop:config>

把異常語句與建表程式碼註解掉再執行一次,就能看到日誌在方法前後被自動插入,而業務程式碼裡完全沒有日誌相關的痕跡——這正是 AOP 的價值所在。

Copyright © Linux教程網 All Rights Reserved