Does Spring @Transactional attribute work on a private method?

后端 未结 8 2156
耶瑟儿~
耶瑟儿~ 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  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.

提交回复
热议问题