你可以如何查看Spring Framework中的类代理代码?

huangapple go评论54阅读模式
英文:

How can I see the class proxy code in Spring Framework?

问题

我想查看Spring中的Transactional注解在运行时生成的代码。我该如何做?
如果这不可能或者难以实现,请告诉我Spring在带有Transactional注解的方法中插入了什么代码。我知道在事务中应该使用entityManager.getTransaction().begin();entityManager.getTransaction().commit();来使用EntityManager。但是在多线程环境中,当许多线程访问同一个EntityManager并调用entityManager.getTransaction().begin();时,它是如何工作的?如果事务已经打开,将会抛出异常。因此,如果Spring确实将这些带有事务的代码插入到方法中,它在多线程环境中是如何工作的?

英文:

I want to see what code is generated on the fly by Transactional annotation in Spring. How can i do this?
If this is impossible or difficult to do, then please tell me what code Spring inserts into the methods annotated with Transactional annotation. I know that using EntityManager in transactions should be used entityManager.getTransaction().begin(); and entityManager.getTransaction().commit();. But how does it work in a multi-threaded environment, when many threads access the same EntityManager and call entityManager.getTransaction().begin();? If a transaction has been opened, an exception will be thrown. Therefore, if Spring inserts exactly this code with transactions into methods, how does it work in a multithreaded environment?

答案1

得分: 1

代理代码没有生成。实际上,这些是一些实现了 InvocationHandler 的静态代码。有关它是如何工作的示例,请参见此链接

在Spring AOP方面,InvocationHandler 的实现是 JdkDynamicAopProxy,它会在某种程度上调用TransactionInterceptor来处理@Transactional

因此,入口点是查看TransactionInterceptor#invoke(MethodInvocation),这些代码会在@Transactional方法周围执行。

英文:

The proxy codes are not generated. It is actually some static codes that implement InvocationHandler. See this for a hello world example for how does it work.

In term of Spring AOP , the implementation of InvocationHandler is JdkDynamicAopProxy which will somehow invokes TransactionInterceptor for @Transactional.

So the entry point is to look at TransactionInterceptor#invoke(MethodInvocation) which are the codes execute around a @Transactional method.

huangapple
  • 本文由 发表于 2023年6月11日 21:14:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定