How to wire up a DataSourceTransactionManager with @Configuration @Beans instead of XML
Typical XML for hooking up a transaction manager in Spring looks like:
<bean id="txManager" cl开发者_C百科ass="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:
- 3.11.4.2 Injecting dependencies
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(){
...
}
精彩评论