亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

[解決] spring service 調用當前類方法事務不生效

標簽:
Spring

今天在测试框架的时候,我想在一个service类的方法中调用 当前类的另一个方法(该方法通过@Transactional开启事务),这时候发现被调用类的事务并没有生效。

    public boolean test1() {        // xxx 业务逻辑
        return test2();
    }    
    @Transactional
    public boolean test2() {
        testMapper.insertSalary("test", UUID.randomUUID().toString());        int a = 10/0;        return true;
    }

WHY? 搜索引擎一番查询之后,了解到问题的关键:
@Transactional 是基于aop生的代理对象开启事务的
PS:不了解代理模式的小伙伴,结尾有传送门

思路

1.spring 的事务是通过 aop 管理的
2.aop 会通过动态代理 为我们生成代理对象,aop 的功能(例如事务)都是在代理对象中实现的

  1. aop 生成的代理类又在 spring 容器中,所以我们只要在 spring 容器中拿到当前这个bean 再去调用 test2() 就可以开启事务了。

解决
import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;/**
 * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
 *
 */@Componentpublic class SpringContextHolder implements ApplicationContextAware {    private static ApplicationContext applicationContext;    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();        return applicationContext;
    }    @SuppressWarnings("unchecked")    public static <T> T getBean(String beanName) {
        assertApplicationContext();        return (T) applicationContext.getBean(beanName);
    }    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();        return applicationContext.getBean(requiredType);
    }    private static void assertApplicationContext() {        if (SpringContextHolder.applicationContext == null) {            throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
        }
    }

}
    public boolean test1() {        // xxx 业务逻辑
        // 在spring容器中 获取当前类的代理类
        return SpringContextHolder.getBean(TestS.class).test2();
    }    
    @Transactional
    public boolean test2() {
        testMapper.insertSalary("test", UUID.randomUUID().toString());        int a = 10/0;        return true;
    }



作者:殷天文
链接:https://www.jianshu.com/p/cb649e6152b6


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
全棧工程師
手記
粉絲
233
獲贊與收藏
1006

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消