@Transactional does not work on method level

前端 未结 2 1494
鱼传尺愫
鱼传尺愫 2021-01-03 02:48

I have a question about Spring 3.2.3 @Transactional annotation. My Service class looks like this:

@Service @Transactional
class InventoryDisclosureBO {

@Aut         


        
相关标签:
2条回答
  • 2021-01-03 03:31

    You cannot call persist() from processDisclosureData() because it belongs to the same class and it will bypass transactional proxy created by Spring for InventoryDisclosureBO. You should call it from other beans to make @Transactional annotations work. When Spring injects a reference to InventoryDisclosureBO bean to other beans it actually injects a reference to InventoryDisclosureBOProxy which contains transactional logic, eg

        class Bean2 {
    
          @Autowire
          private InventoryDisclosureBO idbo;   <-- Spring will inject a proxy here
    
          public void persist(InventoryDisclosureStatus data) {
               idbo.persist(data);     <-- now it will work via proxy
          }
    ...
    
    0 讨论(0)
  • 2021-01-03 03:41

    This is related to how spring generates the transactional proxies.

    In the case where you have @Transactional at the class level, when you call InventoryDisclosureBO.processDisclosureData(), in fact, you're calling a Spring proxy that starts the transaction, and then calls the real implementation.

    If you only have @Transaction in persis(), spring doesn't start a transaction when you call InventoryDisclosureBO.processDisclosureData(), and then it cannot detect that you've called InventoryDisclosureBO.persist()

    So Spring basically ignores the annotation on persist, because it cannot add the transactional proxy.

    As a rule of thumb, the @Transactional annotation should be on a public method, and hopefully quite high in the call hierarchy (otherwise each persist would end up creating a new transaction)

    You might find more information on this other SO question: Method Interceptor on private methods (any non-public methods behave in the same way)

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