java – Spring @Transactional属性是否适用于私有方法?

如果我对Spring bean中的私有方法有一个@Transactional注释,注释是否有效果?

如果@Transactional注释是在一个公共方法,它工作和打开一个事务。

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

  }
}

...

Bean bean = (Bean)appContext.getBean("bean");
bean.doStuff();
最佳答案
答案你的问题是no – @Transactional将没有效果,如果用于注释私有方法。代理生成器将忽略它们。

这在Spring Manual chapter 10.5.6中有记录:

Method visibility and @Transactional

When using proxies, you should apply
the @Transactional annotation only
to methods with public visibility. If
you do annotate protected, private or
package-visible methods with the
@Transactional annotation, no error
is raised, but the annotated method
does not exhibit the configured
transactional settings. Consider the
use of AspectJ (see below) if you need
to annotate non-public methods.

转载注明原文:java – Spring @Transactional属性是否适用于私有方法? - 代码日志