Does Spring @Transactional attribute work on a private method?

后端 未结 8 2044
耶瑟儿~
耶瑟儿~ 2020-11-22 14:03

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

相关标签:
8条回答
  • 2020-11-22 14:25

    Same way as @loonis suggested to use TransactionTemplate one may use this helper component (Kotlin):

    @Component
    class TransactionalUtils {
        /**
         * Execute any [block] of code (even private methods)
         * as if it was effectively [Transactional]
         */
        @Transactional
        fun <R> executeAsTransactional(block: () -> R): R {
            return block()
        }
    }
    

    Usage:

    @Service
    class SomeService(private val transactionalUtils: TransactionalUtils) {
    
        fun foo() {
            transactionalUtils.executeAsTransactional { transactionalFoo() }
        }
    
        private fun transactionalFoo() {
            println("This method is executed within transaction")
        }
    }
    

    Don't know whether TransactionTemplate reuse existing transaction or not but this code definitely do.

    0 讨论(0)
  • 2020-11-22 14:33

    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:

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

    0 讨论(0)
  • The answer your question is no - @Transactional will have no effect if used to annotate private methods. The proxy generator will ignore them.

    This is documented in 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.

    0 讨论(0)
  • 2020-11-22 14:37

    By default the @Transactional attribute works only when calling an annotated method on a reference obtained from applicationContext.

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

    This will open a transaction:

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

    This will not:

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

    Spring Reference: Using @Transactional

    Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

    Consider the use of AspectJ mode (see below) if you expect self-invocations to be wrapped with transactions as well. In this case, there won't be a proxy in the first place; instead, the target class will be 'weaved' (i.e. its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

    0 讨论(0)
  • 2020-11-22 14:44

    Spring Docs explain that

    In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

    Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

    Another way is user BeanSelfAware

    0 讨论(0)
  • 2020-11-22 14:46

    Yes, it is possible to use @Transactional on private methods, but as others have mentioned this won't work out of the box. You need to use AspectJ. It took me some time to figure out how to get it working. I will share my results.

    I chose to use compile-time weaving instead of load-time weaving because I think it's an overall better option. Also, I'm using Java 8 so you may need to adjust some parameters.

    First, add the dependency for aspectjrt.

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.8.8</version>
    </dependency>
    

    Then add the AspectJ plugin to do the actual bytecode weaving in Maven (this may not be a minimal example).

    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
        <version>1.8</version>
        <configuration>
            <complianceLevel>1.8</complianceLevel>
            <source>1.8</source>
            <target>1.8</target>
            <aspectLibraries>
                <aspectLibrary>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aspects</artifactId>
                </aspectLibrary>
            </aspectLibraries>
        </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>compile</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    

    Finally add this to your config class

    @EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
    

    Now you should be able to use @Transactional on private methods.

    One caveat to this approach: You will need to configure your IDE to be aware of AspectJ otherwise if you run the app via Eclipse for example it may not work. Make sure you test against a direct Maven build as a sanity check.

    0 讨论(0)
提交回复
热议问题