有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring建议:代理机制与类或接口上的@Transactional

Spring doc有两个建议:

Spring recommends that you only annotate concrete classes (and methods of 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 works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.

(从http://static.springsource.org/spring/docs/3.0.x/reference/transaction.html

Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. (JDK dynamic proxies are preferred whenever you have a choice).

(从http://static.springsource.org/spring/docs/3.0.x/reference/aop.html#aop-understanding-aop-proxies

我是否正确理解,为了遵循这两个建议,我需要在具体类上有@Transactional注释,但仍然提供一个包含所有事务方法的接口(该类实现),以便Spring可以为该接口使用JDK Dynamicx代理


共 (1) 个答案

  1. # 1 楼答案

    它是这样工作的

    1. 使用方法创建业务接口,不要使用@Transactional

    2. 为上面定义的接口编写一个实现类,并用@Transactional

    由于spring建议使用基于接口的JDK动态代理,因此我们需要有适当的业务接口。 另外,如前所述

    Java annotations are not inherited from interfaces

    我们需要用@Transactional注释具体/实现类方法