javaspringtransactionsannotations

Does Spring @Transactional attribute work on a private method?


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

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

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

  }
}

...

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

Solution

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

    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.

    This has two implications:

    @See Spring Reference: Chapter 9.6 9.6 Proxying mechanisms

    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).