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

标签 java spring proxy spring-jdbc transactional

我正在阅读有关放置事务(接口(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/

相关文章:

Linux 不支持的代理配置

git - git push through network 如何工作? (代理人)

java - GWT - 当选中另一个 CheckboxCell 时,如何以编程方式取消选中一个 CheckboxCell?

java - 将时间戳转换为相对时间

java - 通过 Collection 接口(interface)拒绝的索引向 ArrayList 添加元素

spring - 如何配置Spring Boot嵌入式Tomcat连接超时?

java - Web应用的Ping实现方法

java - 方法类型的 Spring REST 最佳实践

python - 如何在 python 中使用 selenium 运行 headless chrome 和代理?

java - Java EE/JBoss AS 6 中的预身份验证用户