在我的Sping Boot 项目中,我有两个数据源:
@Primary
@Bean(name = "pgDatasource")
public BasicDataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.dbcp2.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.dbcp2.url"));
dataSource.setUsername(env.getProperty("spring.datasource.dbcp2.username"));
dataSource.setPassword(env.getProperty("spring.datasource.dbcp2.password"));
dataSource.setMaxActive(Integer.valueOf(env.getProperty("spring.datasource.dbcp2.max-total")));
dataSource.setMaxIdle(Integer.valueOf(env.getProperty("spring.datasource.dbcp2.max-idle")));
dataSource.setInitialSize(Integer.valueOf(env.getProperty("spring.datasource.dbcp2.initial-size")));
return dataSource;
}
@Bean(name = "h2Datasource")
public BasicDataSource h2DataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("spring.h2.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.h2.datasource.url"));
dataSource.setUsername(env.getProperty("spring.h2.datasource.username"));
dataSource.setPassword(env.getProperty("spring.h2.datasource.password"));
Resource initData = new ClassPathResource("scripts/inmem.sql");
DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initData);
DatabasePopulatorUtils.execute(databasePopulator, dataSource);
return dataSource;
}
这里PostgreSQL的数据源是一个主bean。在我的几个测试中,我想对h2数据库运行一个脚本。为此,我尝试使用@Sql
注解。但是,如果我使用@Sql
,它会对pgDatasource
运行脚本。我可以将h2配置为这些测试的主bean,但是测试方法的主体依赖于pgDatasource
为主bean的配置。
供试品:
@Test
@Sql(scripts = "/clean_login_attempts.sql", executionPhase = AFTER_TEST_METHOD)
void loginAttemptsIncrementTheCount() throws Exception {
unsuccessfulLoginRequest();
unsuccessfulLoginRequest();
unsuccessfulLoginRequest();
LoginAttempt loginAttempt = loginAttemptService.getAttempt("admin");
assertEquals(3, loginAttempt.getAttempt());
}
是否可以为org.springframework.test.context.jdbc.Sql
annotation配置数据源?
1条答案
按热度按时间3wabscal1#
添加
解决了这个问题。