Zonky + Spring Boot + Postgres + Flyway 用户名和密码

Zonky + Spring Boot + Postgres + Flyway with Username and Password

我们正在使用 Zonky 对我们的 Spring 由 Postgres 和 Flyway 支持的启动应用程序进行集成测试。一切都像一个魅力。
但是由于我们有特定的数据库配置,应用程序用户没有 DDL 权限。因此,对于数据库迁移,我们有一个不同的数据库用户(具有 DDL 权限),我们通过 spring.flyway.user 设置了它。不幸的是,为 flyway forces FlywayAutoConfiguration 设置了一个用户名来专门为 Flyway 创建一个内联数据源。这是一个问题,因为 Zonky 在启动 Postgres 实例后,用正确的 url/user/pass 覆盖原始数据源 bean。因此 Flyway 尝试连接不存在的数据库并失败并返回 Connection Refused。 (请参阅存储库中的 issue

由于使用专用凭证为 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");
            }
        }
    }
}