gpt4 book ai didi

java - 什么是基于接口(interface)的代理?

转载 作者:搜寻专家 更新时间:2023-10-31 20:08:53 24 4
gpt4 key购买 nike

我正在阅读有关放置事务(接口(interface)与实现)的位置:

The Spring team's recommendation is that you only annotate concrete classes with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this will only work as you would expect it to if you are using interface-based proxies. The fact that annotations are not inherited means that if you are using class-based proxies then the transaction settings will not be recognised by the class-based proxying infrastructure and the object will not be wrapped in a transactional proxy (which would be decidedly bad). So please do take the Spring team's advice and only annotate concrete classes (and the methods of concrete classes) with the @Transactional annotation.

所以问题是什么是interface-based proxy 究竟是什么,我怎么知道它是否被使用了?它是某种配置还是我实例化/使用实例的方式?

最佳答案

如果 Spring 无法创建 JDK 代理(或者如果您通过将 proxyTargetClass 设置为 true 来强制 Spring 创建 CGLIB 代理),那么代码将不会在事务上下文中执行,因为(如 Spring 文档所述):

The fact that annotations are not inherited means that if you are using class-based proxies then the transaction settings will not be recognised by the class-based proxying infrastructure and the object will not be wrapped in a transactional proxy

所以,我认为您的担忧是:

How can you be sure that Spring does not create a CGLIB proxy

您必须配置基于 AOP 的事务支持。如果您使用 <tx:annotation-driven/> 执行此操作那么 proxy-target-class (false) 的默认值就足够了,尽管可以通过设置来明确这一点:<tx:annotation-driven proxy-target-class=“false"></tx:annotation-driven> .如果您以其他方式配置事务支持(例如,使用 Java 配置),则只需确保 TransactionProxyFactoryBean.proxyTargetClass 的值是假的。

How can you be sure that your @Transactional annotations are respected

这很简单,只需用 @Transactional 注释具体类即可注释而不是注释接口(interface)。这避免了任何代理问题。

综上所述,Spring只要TransactionProxyFactoryBean.proxyTargetClass就应该使用基于接口(interface)的代理但是,如果您注释一个具体类而不是一个实现,那么代理问题将不会影响事务支持。

关于java - 什么是基于接口(interface)的代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45463757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com