最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring 事務(wù)管理三種實現(xiàn)方式詳解

 更新時間:2026年05月08日 15:07:17   作者:一只大袋鼠  
本文主要講解了Spring事務(wù)的三種配置方式,以轉(zhuǎn)賬操作為例,通俗易懂,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友參考下吧

一、前言

在上一篇博客中,我們學(xué)習了 Spring JdbcTemplate 實現(xiàn)轉(zhuǎn)賬操作。但是:如果轉(zhuǎn)賬過程中程序報錯,錢會只扣不加,造成數(shù)據(jù)錯誤!

所以必須使用 Spring 事務(wù)管理,保證轉(zhuǎn)賬要么全部成功,要么全部失敗。本文講解 Spring 事務(wù) 3 種配置方式,基于轉(zhuǎn)賬案例,通俗易懂,適合新手學(xué)習。

二、事務(wù)核心 API

Spring 事務(wù)管理的核心接口:

  1. PlatformTransactionManager:平臺事務(wù)管理器
  2. DataSourceTransactionManager:JDBC / MyBatis 專用實現(xiàn)類
  3. TransactionDefinition:事務(wù)定義(隔離級別、傳播行為)

三、環(huán)境說明

 Maven 依賴(pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.qcby</groupId>
    <artifactId>spring-aop-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- Spring核心 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.31</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.31</version>
        </dependency>
        <!-- 注解支持 -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!-- 測試 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.31</version>
            <scope>test</scope>
        </dependency>
        <!-- 數(shù)據(jù)庫 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- AOP 相關(guān) -->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.31</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.3</version>
        </dependency>
    </dependencies>
</project>

配置文件:application.properties 存放數(shù)據(jù)庫連接信息

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

數(shù)據(jù)庫表結(jié)構(gòu)

CREATE TABLE account(
    name VARCHAR(20),
    money DOUBLE
);
-- 初始化數(shù)據(jù)
INSERT INTO account VALUES ('熊大',1000),('熊二',500);

四、? 方式一:XML 聲明式事務(wù)

1、原理

基于 AOP 切面,在 XML 中配置事務(wù)規(guī)則,對業(yè)務(wù)方法進行增強。

2、完整 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:context="http://www.springframework.org/schema/context"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 加載配置 -->
    <context:property-placeholder location="classpath:application.properties"/>
    <!-- 連接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 1. 事務(wù)管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 2. 事務(wù)通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="pay" isolation="DEFAULT" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 3. AOP 切面配置 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.qcby.demo4.AccountServiceImpl.pay(..))"/>
    </aop:config>
    <!-- Dao & Service -->
    <bean id="accountDao" class="com.qcby.demo4.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="accountService" class="com.qcby.demo4.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>
</beans>

3、業(yè)務(wù)代碼

// Service
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void pay(String out, String in, double money) {
        accountDao.outMoney(out, money);
        // int i = 1 / 0;  開啟異常,事務(wù)回滾
        accountDao.inMoney(in, money);
    }
}

五、? 方式二:XML + 注解事務(wù)

1、步驟

  1. 開啟注解掃描
  2. 開啟事務(wù)注解驅(qū)動
  3. 在 Service 上加 @Transactional

2、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:context="http://www.springframework.org/schema/context"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 注解掃描 -->
    <context:component-scan base-package="com.qcby.demo5"/>
    <context:property-placeholder location="classpath:application.properties"/>
    <!-- 連接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 事務(wù)管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 開啟事務(wù)注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

3、Service 事務(wù)注解

@Service
@Transactional(isolation = Isolation.DEFAULT)
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    @Override
    public void pay(String out, String in, double money) {
        accountDao.outMoney(out, money);
        // int a = 1/0;  報錯自動回滾
        accountDao.inMoney(in, money);
    }
}

六、? 方式三:純注解事務(wù)(完全無 XML)

1、配置類

@Configuration
@ComponentScan("com.qcby.demo6")
@EnableTransactionManagement // 開啟事務(wù)
public class SpringConfig {
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql:///spring_db?useSSL=false&serverTimezone=UTC");
        ds.setUsername("root");
        ds.setPassword("Zhen@777");
        return ds;
    }
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

2、Service 代碼

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    @Override
    public void pay(String out, String in, double money) {
        accountDao.outMoney(out, money);
        accountDao.inMoney(in, money);
    }
}

七、測試代碼(通用)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext_tx.xml")
public class Demo4Test {
    @Autowired
    private AccountService accountService;
    @Test
    public void testPay(){
        accountService.pay("熊大","熊二",100);
        System.out.println("? 轉(zhuǎn)賬成功(事務(wù)已生效)");
    }
}

八、事務(wù)三種方式

方式優(yōu)點
XML 聲明式事務(wù)無侵入、不修改代碼
XML + 注解事務(wù)簡單易用、最常用
純注解事務(wù)無配置文件、簡潔

到此這篇關(guān)于Spring 事務(wù)管理三種實現(xiàn)方式詳解的文章就介紹到這了,更多相關(guān)Spring 事務(wù)管理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

桂阳县| 额尔古纳市| 宜章县| 噶尔县| 鲜城| 徐闻县| 龙里县| 浮梁县| 马关县| 丰都县| 新龙县| 六枝特区| 仁化县| 黎川县| 大足县| 开封县| 崇州市| 华阴市| 措勤县| 松潘县| 临澧县| 肇庆市| 万载县| 潜江市| 定陶县| 鄂托克旗| 衡山县| 平遥县| 酒泉市| 廊坊市| 盐津县| 抚顺市| 神池县| 恩施市| 海宁市| 绥宁县| 商城县| 汪清县| 宣武区| 中宁县| 绥化市|