Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wire up a DataSourceTransactionManager with @Configuration @Beans instead of XML

Tags:

spring

Typical XML for hooking up a transaction manager in Spring looks like:

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="myDataSource" />
</bean>

<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    .... properties go here ....
</bean>

How do I accomplish the same thing with code?

@Configuration
public class MyConfig {
  @Bean
  public DataSource myDataSource() {
       return new DataSource(); /// and set properties, etc.
  }

  @Bean
  public DataSourceTransactionManager txManager() {
       --> What goes here? <--
  }
}

Specifically, how do I get txManager wired up to the myDataSource singleton via code?

like image 621
Adam Vandenberg Avatar asked Jun 29 '11 13:06

Adam Vandenberg


2 Answers

Since DataSourceTransactionManager has a constructor that takes DataSource, you can do the following (otherwise you would need to call setDataSource()):

@Bean   
public DataSourceTransactionManager txManager() {
    return new DataSourceTransactionManager(myDataSource());
}

See also:

  • 3.11.4.2 Injecting dependencies
like image 74
axtavt Avatar answered Nov 16 '22 00:11

axtavt


You can also use multiple transactionManager

     @Configuration
        public class MyConfig {
          @Bean
          public DataSource myDataSource1() {
               return new DataSource(); /// and set properties, etc.
          }

          @Bean
          @Qualifier("txManager1")
          public DataSourceTransactionManager txManager1() {
               return new DataSourceTransactionManager(myDataSource1());
          }

          @Bean
          public DataSource myDataSource2() {
               return new DataSource(); /// and set properties, etc.
          }

          @Bean
          @Qualifier("txManager2")
          public DataSourceTransactionManager txManager2() {
             return new DataSourceTransactionManager(myDataSource2());
          }

    }

Then when use @Transactional you can define the transactionManager you want :

@Transactional("txManager1")
public Object getSomeData(){
    ...
}

@Transactional("txManager2")
public Object getSomeOtherData(){
    ...
}
like image 23
Nicolas CHALAUX Avatar answered Nov 16 '22 00:11

Nicolas CHALAUX