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?
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:
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(){
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With