@Transactional与静态方法 [英] @Transactional with static method

查看:912
本文介绍了@Transactional与静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们不能使用@Transactional静态方法来管理spring项目中的事务?

Why cant we use @Transactional for static methods to manage the transactions in my spring Project ?

@Transactional对于非静态方法效果很好,但对于某些特定原因,它不适用于静态方法?

@Transactional works well for non static method but not for static methods any specific reason ?

推荐答案

为了理解为什么您所提议的东西行不通,您必须首先在较高的层次上理解Spring如何处理使用@Transactional的bean.

In order to understand why something like what you are proposing does not work you have to first understand at a high level how Spring handles beans that use @Transactional.

当将方法或类注释为@Transactional并使其成为Spring Bean时,Spring会有效地为该类创建代理(使用JDK Dynamic代理或CGLIB代理).这意味着每当使用您的类时(即从Spring托管代码中),不是立即调用您的代码,而是首先执行所需操作的代理,然后才调用您的代码(在缓存支持的情况下,代码甚至根本不会被调用). 这里要记住的关键一点是,调用代码(如果需要的话,调用站点)根本不会改变,并且所需的目标方法(代理方法)的调用是由JVM使用相同的字节码( invokevirtual invokeinterface ).

When you annotate a method or the class as @Transactional and make it a Spring Bean, Spring effectively creates a proxy for that class (using JDK Dynamic proxies or CGLIB proxies). That means that whenever your class is used (from Spring managed code that is), it's not your code that gets called immediately, but the proxy which first does whatever is needed, and then your code is called (in the case of caching support your code would perhaps not even be called at all). A key thing to remember here is that the invoking code (the call site if you will) does not change at all, and the invocation of to the required target method (the proxy method) is performed by the JVM using the same bytecode (invokevirtual or invokeinterface).

记住这一点,不支持static的原因就很清楚了. 您无法为静态方法创建代理!当然,Java Dynamic Proxies无法做到这一点,CGLIB也不能做到这一点.

With that in mind, the reason that static is not supported becomes clear. You can't create a proxy for static method! Of course Java Dynamic Proxies cannot do this, and neither can CGLIB.

支持这种功能将需要更改调用代码的字节码,因为调用静态方法是通过字节码中的invokestatic实现的,从而将目标方法硬编码.

Supporting such a feature would require changing the bytecode of the invoking code, since calling a static method is implemented via invokestatic in bytecode, which hard-codes the target method.

Spring文档的一部分详细说明了Spring AOP

This part of the Spring documentation explains Spring AOP in details

这篇关于@Transactional与静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆