0

我想根据用户登录连接不同的数据库,所以我将 TransactionManager bean 作为原型范围,它每次都在创建 transacionManager bean,并且运行良好。但是,当应用范围扩大时,它会变得多稳定?

有任何想法吗 ?谢谢。

@Bean(initMethod = "init", destroyMethod = "destroy")
@Scope(value = "prototype")
public PlatformTransactionManager transactionManager() {
4

1 回答 1

0

使用它作为原型不是一个好的做法。这实际上意味着每次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
    }
}
于 2014-01-03T03:59:06.797 回答