Spring @Transactional 属性是否适用于私有方法? [英] Does Spring @Transactional attribute work on a private method?

查看:29
本文介绍了Spring @Transactional 属性是否适用于私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 @Transactional - Spring bean 中私有方法的注解,注解有什么作用吗?

If I have a @Transactional -annotation on a private method in a Spring bean, does the annotation have any effect?

如果 @Transactional 注释在公共方法上,它会起作用并打开一个事务.

If the @Transactional annotation is on a public method, it works and open a transaction.

public class Bean {
  public void doStuff() {
     doPrivateStuff();
  }
  @Transactional
  private void doPrivateStuff() {

  }
}

...

Bean bean = (Bean)appContext.getBean("bean");
bean.doStuff();

推荐答案

这个问题既不是私有的也不是公开的,问题是:它是如何调用的,你使用的是哪个 AOP 实现!

The Question is not private or public, the question is: How is it invoked and which AOP implementation you use!

如果您使用(默认)Spring Proxy AOP,那么只有在调用通过代理时才会考虑 Spring 提供的所有 AOP 功能(如 @Transactional).-- 如果从另一个 bean 调用带注释的方法,通常就是这种情况.

If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transactional) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.

这有两个含义:

  • 因为不能从另一个 bean 调用私有方法(反射除外),所以不考虑它们的 @Transactional 注释.
  • 如果该方法是公共的,但它是从同一个 bean 调用的,则也不会考虑它(此语句仅在(默认)使用 Spring Proxy AOP 时才正确).

@See Spring 参考:第 9.6 章 9.6 代理机制

恕我直言,您应该使用 aspectJ 模式,而不是 Spring Proxies,这将克服这个问题.并且 AspectJ 事务方面甚至被编织到私有方法中(检查 Spring 3.0).

IMHO you should use the aspectJ mode, instead of the Spring Proxies, that will overcome the problem. And the AspectJ Transactional Aspects are woven even into private methods (checked for Spring 3.0).

这篇关于Spring @Transactional 属性是否适用于私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆