Spring 数据 JDBC 测试容器数据源

Spring Data JDBC Testcontainers DataSource

使用 spring 引导 + spring 数据 jdbc 我必须自己连接 DataSource bean。像这样:

@Bean
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(this.environment.getRequiredProperty("url"));
        hikariConfig.setUsername("user");
        hikariConfig.setDriverClassName("org.postgresql.Driver");
        hikariConfig.setPassword("password");
        return new HikariDataSource(hikariConfig);
    }

当我想使用测试容器进行测试时,我还必须声明一个 DataSource bean:

@Bean
        @Primary
        DataSource testDataSource() {

            if (POSTGRESQL_CONTAINER == null) {
                PostgreSQLContainer<?> container = new PostgreSQLContainer<>(DockerImageName.parse("postgres").withTag("9.6.12"));
                container.withInitScript("schema.sql");
                container.start();
                POSTGRESQL_CONTAINER = container;
            }
            PGSimpleDataSource dataSource = new PGSimpleDataSource();
            dataSource.setUrl(POSTGRESQL_CONTAINER.getJdbcUrl());
            dataSource.setUser(POSTGRESQL_CONTAINER.getUsername());
            dataSource.setPassword(POSTGRESQL_CONTAINER.getPassword());

            return dataSource;
        }

使用我的 SpringBootTest 测试,我必须 ComponentScan 几乎所有的包,因为我不想模拟所有其他 bean。
所以我的问题是:
我可以以某种方式排除主要的 DataSource 仅用于测试用例吗?
(我目前的解决方法是将测试 DataSource 定义为 Primary
但是尽管如此,我的 Context 中有两个 DataSource 个豆子,即使我只需要一个。

https://github.com/wearearima/spring-data-jdbc-testcontainers的例子似乎表明根本不需要定义自己的DataSource。

参见https://github.com/wearearima/spring-data-jdbc-testcontainers/blob/master/src/test/java/eu/arima/springdatajdbctestcontainers/AccountRepositoryTest.java#L94如何将 TestContainers 托管数据库的属性传递给 Spring 引导:

 @DynamicPropertySource
    static void postgresqlProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgresqlContainer::getJdbcUrl);
        registry.add("spring.datasource.username", postgresqlContainer::getUsername);
        registry.add("spring.datasource.password", postgresqlContainer::getPassword);
    }