用于在Spring中连接事务管理器的典型XML如下所示:
<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>
如何使用代码完成同样的事情?
@Configuration
public class MyConfig {
@Bean
public DataSource myDataSource() {
return new DataSource(); /// and set properties, etc.
}
@Bean
public DataSourceTransactionManager txManager() {
--> What goes here? <--
}
}
具体来说,如何通过代码将txManager连接到myDataSource单例?
答案 0 :(得分:6)
由于DataSourceTransactionManager
有一个带DataSource
的构造函数,您可以执行以下操作(否则您需要调用setDataSource()
):
@Bean
public DataSourceTransactionManager txManager() {
return new DataSourceTransactionManager(myDataSource());
}
另见:
答案 1 :(得分:2)
您还可以使用多个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());
}
}
然后当使用@Transactional时,您可以定义所需的transactionManager:
@Transactional("txManager1")
public Object getSomeData(){
...
}
@Transactional("txManager2")
public Object getSomeOtherData(){
...
}