Java 类org.springframework.transaction.annotation.TransactionManagementConfigurer 实例源码

项目:class-guard    文件:TransactionalTestExecutionListener.java   
/**
 * Get the {@link PlatformTransactionManager transaction manager} to use
 * for the supplied {@link TestContext test context}.
 * @param testContext the test context for which the transaction manager
 * should be retrieved
 * @return the transaction manager to use, or {@code null} if not found
 * @throws BeansException if an error occurs while retrieving the transaction manager
 * @see #getTransactionManager(TestContext, String)
 */
protected final PlatformTransactionManager getTransactionManager(TestContext testContext) {
    BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();
    String tmName = retrieveConfigurationAttributes(testContext).getTransactionManagerName();

    try {
        // look up by type and explicit name from @TransactionConfiguration
        if (StringUtils.hasText(tmName) && !DEFAULT_TRANSACTION_MANAGER_NAME.equals(tmName)) {
            return bf.getBean(tmName, PlatformTransactionManager.class);
        }

        if (bf instanceof ListableBeanFactory) {
            ListableBeanFactory lbf = (ListableBeanFactory) bf;

            // look up single bean by type
            Map<String, PlatformTransactionManager> txMgrs = BeanFactoryUtils.beansOfTypeIncludingAncestors(
                lbf, PlatformTransactionManager.class);
            if (txMgrs.size() == 1) {
                return txMgrs.values().iterator().next();
            }

            // look up single TransactionManagementConfigurer
            Map<String, TransactionManagementConfigurer> configurers = BeanFactoryUtils.beansOfTypeIncludingAncestors(
                lbf, TransactionManagementConfigurer.class);
            if (configurers.size() > 1) {
                throw new IllegalStateException(
                    "Only one TransactionManagementConfigurer may exist in the ApplicationContext");
            }
            if (configurers.size() == 1) {
                return configurers.values().iterator().next().annotationDrivenTransactionManager();
            }
        }

        // look up by type and default name from @TransactionConfiguration
        return bf.getBean(DEFAULT_TRANSACTION_MANAGER_NAME, PlatformTransactionManager.class);

    } catch (BeansException ex) {
        if (logger.isWarnEnabled()) {
            logger.warn("Caught exception while retrieving transaction manager for test context " + testContext, ex);
        }
        throw ex;
    }
}