Spring 下默认事务机制中@Transactional 无效的原因

本文详细探讨了Spring框架中@Transactional注解的使用限制与有效性条件。通过具体示例代码演示了不同场景下事务管理的行为表现,包括私有方法、公共方法及接口调用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:https://www.cnblogs.com/milton/p/6046699.html
Spring中 @Transactional 注解的限制
1. 同一个类中, 一个nan-transactional的方法去调用transactional的方法, 事务会失效

If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transational) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.
  1. 在private方法上标注transactional, 事务无效
When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

这里有一个详细的说明 http://stackoverflow.com/questions/4396284/does-spring-transactional-attribute-work-on-a-private-method

测试代码
TestCase01.java

package com.rockbb.test.api.service;


public interface TestCase01 {
    void init();
    void clean();
    void txnInLocalPrivate();
    void txnInLocalPublic();
    void txnInOpenPublic();
    void txnInOpenPublicByInvokePrivate();
    void txnInOpenPublicByInvokePublic();
}

TestCase01Impl.java

package com.rockbb.test.impl.service.impl;

import com.rockbb.test.api.dto.AccountDTO;
import com.rockbb.test.api.dto.AccountDetailDTO;
import com.rockbb.test.api.service.TestCase01;
import com.rockbb.test.impl.mapper.AccountDetailMapper;
import com.rockbb.test.impl.mapper.AccountMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Repository("testCase01")
public class TestCase01Impl implements TestCase01 {
    @Resource(name="accountMapper")
    private AccountMapper accountMapper;
    @Resource(name="accountDetailMapper")
    private AccountDetailMapper accountDetailMapper;

    @Resource(name="testCase01")
    private TestCase01 testCase01;

    /**
     * 无效, 未回退
     *
     * 结论: 在私有方法上加事务注解无效
     */
    @Override
    public void txnInLocalPrivate() {
        localPrivate();
    }

    /**
     * 无效, 未回退
     *
     * 结论: 在公有方法上事务注解, 再通过接口方法调用, 无效
     */
    @Override
    public void txnInLocalPublic() {
        localPublic();
    }

    /**
     * 有效, 无论下面调用的是否是私有方法
     *
     * 结论: 在接口方法上加事务, 无论下面调用的是否是私有方法, 都有效
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void txnInOpenPublic() {
        localPrivate();
    }

    @Override
    public void txnInOpenPublicByInvokePrivate() {

    }

    /**
     *
     * 结论: 普通接口方法直接调用同类带事务的方法, 无效. 通过接口调用则有效
     */
    @Override
    public void txnInOpenPublicByInvokePublic() {
        //txnInOpenPublic(); // 无效
        testCase01.txnInOpenPublic(); // 有效
    }

    @Override
    public void init() {
        accountMapper.truncate();
        for (int i = 0; i < 10; i++) {
            BigDecimal amount = BigDecimal.valueOf(i * 10);
            add(String.valueOf(i), BigDecimal.ZERO);
            increase(String.valueOf(i), BigDecimal.valueOf(100 + i));
        }
    }

    @Override
    public void clean() {
        accountMapper.truncate();
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    private void localPrivate() {
        AccountDTO dto = new AccountDTO().initialize();
        dto.setId("test");
        dto.setAmount(BigDecimal.ZERO);
        accountMapper.insert(dto);
        throw new RuntimeException("localPrivate");
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void localPublic() {
        AccountDTO dto = new AccountDTO().initialize();
        dto.setId("test");
        dto.setAmount(BigDecimal.ZERO);
        accountMapper.insert(dto);
        throw new RuntimeException("localPublic");
    }

    public void openPublic() {
        AccountDTO dto = new AccountDTO().initialize();
        dto.setId("test");
        dto.setAmount(BigDecimal.ZERO);
        accountMapper.insert(dto);
        throw new RuntimeException("openPublic");
    }

    private int add(String id, BigDecimal amount) {
        AccountDTO dto = new AccountDTO().initialize();
        dto.setId(id);
        dto.setAmount(amount);
        return accountMapper.insert(dto);
    }

    private int increase(String id, BigDecimal amount) {
        AccountDTO dto = accountMapper.select(id);
        AccountDetailDTO detail = new AccountDetailDTO().initialize();
        detail.setAmount(amount);
        detail.setPreAmount(dto.getAmount());
        dto.setAmount(dto.getAmount().add(amount));
        detail.setPostAmount(dto.getAmount());
        if (accountMapper.update(dto) != 1) {
            throw new RuntimeException();
        }
        return accountDetailMapper.insert(detail);
    }
}

TestCase02.java

package com.rockbb.test.api.service;

public interface TestCase02 {
    void txnInOpenPublicByPublic();
    void txnInOpenPublicByPrivate();
}

TestCase02Impl.java

package com.rockbb.test.impl.service.impl;

import com.rockbb.test.api.service.TestCase01;
import com.rockbb.test.api.service.TestCase02;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository("testCase02")
public class TestCase02Impl implements TestCase02 {
    @Resource(name="testCase01")
    private TestCase01 testCase01;

    /**
     * 有效
     *
     * 结论: 在接口方法上加事务, 再被他类的接口方法调用, 无论此接口方法是否加事务, 都有效
     */
    @Override
    public void txnInOpenPublicByPublic() {
        testCase01.txnInOpenPublic();
    }

    /**
     * 有效
     *
     * 结论: 在接口方法上加事务, 再被他类的私有方法调用后, 依然有效
     */
    @Override
    public void txnInOpenPublicByPrivate() {
        localPrivate();
    }

    private void localPrivate() {
        testCase01.txnInOpenPublic();
    }
}

测试样例 AccountCheckTest.java

package com.rockbb.test.test;

import com.rockbb.test.api.service.TestCase01;
import com.rockbb.test.api.service.TestCase02;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring/spring-commons.xml"})
public class AccountCheckTest {
    private static final Logger logger = LoggerFactory.getLogger(AccountCheckTest.class);
    @Resource(name="testCase01")
    private TestCase01 testCase01;
    @Resource(name="testCase02")
    private TestCase02 testCase02;

    @Test
    public void test01() {
        testCase01.init();
        try {
            testCase01.txnInLocalPrivate();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Test
    public void test02() {
        testCase01.init();
        try {
            testCase01.txnInLocalPublic();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Test
    public void test03() {
        testCase01.init();
        try {
            testCase01.txnInOpenPublic();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Test
    public void test04() {
        testCase01.init();
        try {
            testCase02.txnInOpenPublicByPublic();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Test
    public void test05() {
        testCase01.init();
        try {
            testCase02.txnInOpenPublicByPrivate();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Test
    public void test06() {
        testCase01.init();
        try {
            testCase01.txnInOpenPublicByInvokePublic();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

结论

1.@Transactional 加于private方法, 无效
2.@Transactional 加于未加入接口的public方法, 再通过普通接口方法调用, 无效
3.@Transactional 加于接口方法, 无论下面调用的是private或public方法, 都有效
4.@Transactional 加于接口方法后, 被本类普通接口方法直接调用, 无效
5.@Transactional 加于接口方法后, 被本类普通接口方法通过接口调用, 有效
6.@Transactional 加于接口方法后, 被它类的接口方法调用, 有效
7.@Transactional 加于接口方法后, 被它类的私有方法调用后, 有效
总结: Transactional是否生效, 仅取决于是否加载于接口方法, 并且是否通过接口方法调用(而不是本类调用)

还有一种情况:就是spring配置文件里配置了两个 (这个是我自己犯的错误,一般不是种情况)

<tx:annotation-driven mode="proxy" transaction-manager="sqlServerTransactionManager" />
<think>好的,我需要回答用户关于Spring框架中@Transactional注解的用法和功能的问题。首先,我得整理一下现有的参考资料,确保涵盖用户提到的各个要点。用户提到了使用说明、功能介绍、官方文档和最佳实践,所以需要从这几个方面展开。 首先,@Transactional注解的基本功能是声明式事务管理。根据引用[1],Spring事务管理分为编程式和声明式,这里重点在声明式。需要说明注解的作用范围,比如类或方法级别,并提到默认的回滚行为是仅运行时异常。同时,用户可能想知道如何扩展回滚到其他异常,比如检查型异常,这时候可以用rollbackFor属性。 接下来是事务传播机制,引用[2]提到了传播机制,比如REQUIRED、REQUIRES_NEW等,需要简要解释这些传播行为的含义,以及如何通过propagation属性设置。同时,事务失效的场景也是一个重点,比如自调用问题、非public方法等,引用[3]指出非public方法会导致事务不生效,这点必须强调。 然后要整理官方文档的要点,引用[2]的链接是Spring官方文档,可以提到推荐用户查阅该链接获取详细信息。此外,最佳实践部分需要结合资料中的内容,比如正确设置rollbackFor、避免自调用、使用public方法等。 还需要注意格式要求,用户提到行内数学表达式用$...$,不过这个问题可能不涉及数学公式,但需要确保其他格式正确,如代码块用```包裹,引用标识自然添加在段落末尾。同时生成相关问题,参考示例中的结构,最后列出相关问题。 现在检查是否有遗漏的信息。比如,引用[1]中的异常继承体系图虽然有展示,但可以提到运行时异常和检查型异常的区别。事务传播机制的不同类型可能需要更详细的例子,但用户可能只需要基本说明。另外,事务失效的其他场景,如异常被捕获未抛出,或者数据库引擎不支持事务,这些可能需要补充。 最后,确保回答结构清晰,分点说明,符合用户要求的层次结构,并引用正确的来源。同时,生成的三个相关问题需要相关且有价值,帮助用户深入理解。</think>### Spring @Transactional 注解使用说明与功能介绍 #### 1. 核心功能 - **声明式事务管理**:通过注解简化事务配置,替代编程式事务管理[^1]。 - **事务范围控制**:支持类或方法级别的事务声明,方法级注解会覆盖类级配置。 - **默认回滚规则**:仅对运行时异常(`RuntimeException`)及其子类触发回滚,检查型异常(如`IOException`)默认不触发回滚。 - **自定义回滚**:通过`@Transactional(rollbackFor = Exception.class)`扩展回滚范围。 #### 2. 事务传播机制 通过`propagation`属性配置事务边界行为,常见选项: - `REQUIRED`(默认):存在事务则加入,否则新建 - `REQUIRES_NEW`:始终新建事务,挂起当前事务 - `NESTED`:嵌套事务执行 - `SUPPORTS`:存在事务则加入,否则无事务运行 [完整传播行为参考官方文档](https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/tx-propagation.html)[^2] #### 3. 使用规范(官方建议) ```java @Transactional public void updateOrder(Order order) { // 业务逻辑 } ``` - **可见性要求**:必须作用于`public`方法,私有/保护方法注解无效[^3] - **代理机制**:基于AOP代理实现,非Spring管理对象无效 - **自调用失效**:类内部方法互相调用会导致事务失效 #### 4. 最佳实践 1. **明确回滚异常** ```java @Transactional(rollbackFor = {SQLException.class, IOException.class}) ``` 2. **超时设置** ```java @Transactional(timeout = 30) // 单位:秒 ``` 3. **只读事务优化** ```java @Transactional(readOnly = true) ``` 4. **避免嵌套事务复杂度** 谨慎使用`REQUIRES_NEW`,可能引发死锁 #### 5. 典型失效场景 | 场景 | 解决方案 | |---------------------|----------------------------| | 非public方法 | 改用public修饰 | | 自调用 | 通过AopContext代理调用 | | 异常被捕获未抛出 | 在catch块抛出`throw new RuntimeException(e)` | | 数据库引擎不支持事务| 确认使用InnoDB等支持事务的引擎 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值