Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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 open a transaction.

public class Bean {

  public void doStuff() {

     doPrivateStuff();

  }

  @Transactional

  private void doPrivateStuff() {

  }

}

...

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

bean.doStuff();

1 Answer

0 votes
by (46k points)

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 @Transational) 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:

  • Because private methods must not be invoked from another bean (the exception is reflection), their @Transactional Annotation is not taken into account.
  • If the method is public, but it is invoked from the same bean, it will not be taken into account either (this statement is only correct if (default) Spring Proxy AOP is used).

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...