通过接口自动装配时,派生类方法的Spring @Transactional是否生效?
调用bean.method()是否遵循@Transactional事务规则?
结论:会遵循@Transactional注解的事务规则
原因说明:
- Spring默认采用JDK动态代理实现事务管理,当目标类实现了接口时,Spring会为该接口生成代理对象。
- 示例代码中
SomeComponent注入的Iface bean,实际是Spring生成的代理实例,而非Derived类的原始对象。 - 调用
bean.method()时,代理对象会先执行事务拦截逻辑(如开启事务、执行完逻辑后提交/异常时回滚),再调用Derived类的method()方法,因此@Transactional注解的规则会正常生效。
示例代码:
public interface Iface { void method(); } @Component public class Derived implements Iface { @Override @Transactional public void method() { // some logic } } @Component public class SomeComponent { @Autowired private Iface bean; public void someCall() { bean.method(); } }
内容的提问来源于stack exchange,提问作者flamasterrr
相关产品推荐
相关产品推荐

