使用它作为原型不是一个好的做法。这实际上意味着每次transactionManager()
调用时TransactionManager
都会创建一个新的,这是多余的资源消耗,因为每个TransactionManager
配置的单个实例就足够了。
相反,创建一些工厂 bean,您可以调用它TransactionManagerFactory
,它公开了一个 getter,例如PlatformTransactionManager getUserTxManager(SomeRelevantUserDetails)
. 该工厂将为PlatformTransactionManager
各种 DB 供应商创建各种 s,每个都只创建一次,并根据 .将其返回给调用者SomeRelevantUserDetails
。
TransactionManagerFactory 类:
@Component
public class TransactionManagerFactory {
private final PlatformTransactionManager mySqlTxManager;
private final PlatformTransactionManager db2TxManager;
private final PlatformTransactionManager hsqlTxManager;
@Autowired
protected TransactionManagerFactory(
@Qualifier("mySqlTxManager") PlatformTransactionManager mySqlTxManager
@Qualifier("db2TxManager") PlatformTransactionManager db2TxManager
@Qualifier("hsqlTxManager") PlatformTransactionManager hsqlTxManager) {
this.mySqlTxManager = mySqlTxManager;
this.db2TxManager = db2TxManager;
this.hsqlTxManager = hsqlTxManager;
}
public PlatformTransactionManager getUserTxManager(SomeRelevantUserDetails userDetails) {
PlatformTransactionManager userTxManager = // put here logic to determine
return userTxManager;
}
}
其他需要依赖于用户的事务管理器的服务:
@Component
public class UsesTxManagerFactory {
private final TransactionManagerFactory txManagerFactory;
@Autowired
protected UsesTxManagerFactory(TransactionManagerFactory txManagerFactory) {
this.txManagerFactory = txManagerFactory;
}
public void someMethod() {
SomeRelevantUserDetails userDetails = // create the relevant details
PlatformTransactionManager txManager = getUserTxManager(userDetails);
// perform transaction
}
}