What is the scope of @EnableTransactionManagement?

I'm trying to figure out where to place the @EnableTransactionManagement annotation in case of multiple JavaConfig contexts?

Consider the following scenario: I have a JPA config in JPAConfig.java and AppConfig.java with a set of beans services. Then I make up the general application configuration in RootConfig.java.

I define a transaction manager in JPAConfig.java and also allow scanning for JPA repositories - since those who are subject to transactional behavior, I put @EnableTransactionManagement on top of JPAConfig and it works.

However, some beans services must also have transactional methods, for example. Access to multiple repositories in a single transaction. Should I also put @EnableTransactionManagement on top of AppConfig? A look at the implementation of this annotation seems to me that such an approach can lead to an override of some beans. And actually it does not work for me.

 @Configuration @EnableTransactionManagement @EnableJpaRepositories("com.mypackage.repositories") public class JPAConfig { // ... here are EntityManager and PlatformTransactionManager beans } @Configuration @ComponentScan("com.mypackage.services") // @EnableTransactionManagement // - ??? public class AppConfig { } @Configuration @Import({AppConfig.class, JPAConfig.class}) public class RootConfig { } 

Appreciate any advice.

+6
source share
1 answer

After some experiments, I seem to have found the answer myself:

  • There is no need to configure @EnableTransactionManagement on every part of the contextual configuration, although it does matter how early this annotation is detected, since it registers an internalTransactionAdvisor which actually processes @Transactional annotations on the generated beans.
  • In my case, I @Import contexts in the @Import , so the PersistenceConfig that contains @EnableTransactionManagement is the first. After that, beans from other parts can use the AOP deal declaration.
  • Another caveat relates to the simultaneous use of @EnableTransactionManagement and @EnableGlobalMethodSecurity . To ensure the security of global methods, post-processing bean is used, which seems to require connecting the entire security configuration. BeanPostProcessors are created at an early stage of context launch, so you cannot use declarative @Transactional in any bean that is needed to load spring security (in my case UserDetailsContextMapper ) - the adviser has not been created yet!
+10
source

Source: https://habr.com/ru/post/975703/


All Articles