Home » Java » On configuring two transaction managers which one will be used on @Transactions without explicitly specifying Transaction manager?

On configuring two transaction managers which one will be used on @Transactions without explicitly specifying Transaction manager?

Posted by: admin October 26, 2017 Leave a comment

Questions:

I’ve configured two transaction managers

One in XML Config

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
</bean>

<aop:config>
    <aop:advisor pointcut="execution(* com.myorg.*Service.*(..))" advice-ref="transactionAdvice"/>
</aop:config>

<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
</tx:advice>

Other in Java config

@Bean("transactionManager")
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

But when I use @Transactional annotation it appears to me that Transaction manager defined in XML is being used even when point cut does not match.

I want that on execution that matches pointcut transaction manager defined in AOP to be used
and on @Transactional annotation transaction manger defined in Java config to be used.

For some reason I can not explicitly specify transaction manager name in @Transactional annotation like @Transactional(“transactionManager”).

Is there any way to achieve this ?

Answers:

In spring boot (and i guess it should work for spring as well) I do the following to let spring know what is the default transaction manager to be used with @Transactional annotation:

@Configuration
public class CustomTransactionManagementConfiguration implements TransactionManagementConfigurer, ApplicationContextAware {

    private ApplicationContext applicationContext;

    /**
     * @return default transaction manager for rogue {@link Transactional} annotations
     */
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return applicationContext.getBean("myTransactionManagerQualifier", PlatformTransactionManager.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}