【问题标题】:Zonky + Spring Boot + Postgres + Flyway with Username and Password带有用户名和密码的 Zonky + Spring Boot + Postgres + Flyway
【发布时间】:2019-11-22 09:48:01
【问题描述】:
我们正在使用 Zonky 对由 Postgres 和 Flyway 支持的 Spring Boot 应用程序进行集成测试。一切都像魅力一样。
然而,由于我们有特定的数据库配置,应用程序用户没有 DDL 权限。所以对于数据库迁移,我们有一个不同的数据库用户(具有 DDL 权限),我们通过spring.flyway.user 设置。不幸的是,为 flyway 设置用户名会强制 FlywayAutoConfiguration 专门为 Flyway 创建一个内联数据源。这是一个问题,因为 Zonky 在启动 Postgres 实例后,会使用具有正确 url/user/pass 的 bean 覆盖原始数据源 bean。因此 Flyway 尝试连接不存在的数据库并以Connection Refused 失败。 (参见存储库中的issue)
【问题讨论】:
标签:
spring
postgresql
spring-boot
flyway
【解决方案1】:
由于使用专用凭据为 Flyway 创建的数据源不是 bean,Zonky 对此无能为力。
一种解决方案是为 Flyway 创建一个数据源 bean,并使用 @FlywayDataSource 对其进行注释。但这意味着您还必须创建主数据源并将其设为@Primary。
在我们的例子中,我们使用了 Spring Boot 创建的数据源 bean,所以我们没有走上面的解决方案。相反,我们在集成测试中添加了以下内容:
public class SpringFlywayCredentialsInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext c) {
for (PropertySource<?> s : c.getEnvironment().getPropertySources()) {
if (s.containsProperty("spring.flyway.user")
&& s instanceof MapPropertySource) {
((MapPropertySource) s).getSource().remove("spring.flyway.user");
}
}
}
}