【发布时间】:2021-07-28 11:26:10
【问题描述】:
使用 spring boot + spring data 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);
}
当我想使用 testcontainers 进行测试时,我还必须声明一个 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 bean,即使我只需要一个。
【问题讨论】:
-
这能回答你的问题吗? exclude @Component from @ComponentScan
-
谢谢。我会试试这个。顺便一提。您是否在下面查看了 Wim Deblauwe 的答案?此代码中没有声明专用的
DataSource。这在 Spring Data JDBC 中不是必须的吗?我只是好奇...... -
Spring Boot 可以创建您的数据源,这似乎与 Wims 答案一起使用,其中在动态属性源中配置了必要的信息。
标签: spring-boot testcontainers spring-data-jdbc