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

查看:55
本文介绍了@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 如何处理使用 @交易.

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 动态代理或 CGLIB 代理).这意味着无论何时使用您的类(来自 Spring 托管代码),并不是您的代码立即被调用,而是代理首先执行所需的任何操作,然后调用您的代码(在缓存支持您的情况下)甚至可能根本不会调用代码).这里要记住的一个关键是调用代码(调用站点,如果你愿意的话)根本没有改变,对所需目标方法(代理方法)的调用是由 JVM 使用相同的字节码(invokevirtualinvokeinterface).

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).

考虑到这一点,不支持静态的原因就很清楚了.您不能为静态方法创建代理!当然,Java 动态代理不能做到这一点,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天全站免登陆