【问题标题】:Flyway 6 JavaMigrations with Native Dependency Injection for Spring BeansFlyway 6 JavaMigrations with Native Dependency Injection for Spring Beans
【发布时间】:2020-10-09 11:31:13
【问题描述】:

我已经看到许多很棒的解决方法来创建 Flyway JavaMigrations 并使用 @DependsOnApplicationContextAware(例如 https://stackoverflow.com/a/48242865/5244937)注入 Spring Bean。

然而,Flyway 6 文档的一部分声称依赖注入对于 Spring Beans 原生是可能的:

是真的吗?这将如何运作?

【问题讨论】:

  • 通过这一行:ApplicationContext applicationContext = ...; // 获取 Spring 的 ApplicationContext 的引用。
  • 到目前为止,我只使用了基于 SQL 的迁移和 Flyways 自动发现功能。我是否正确理解这将不再适用于这种方法,而是我需要.. - 手动启动迁移? - 使用模式 (1) 实例化 Spring Bean / FlywayMigrationInitializer,(2) 使用 .javaMigrations(..) 手动查找迁移和 (3) 通过 flyway.migrate(); 手动启动 flyway?
  • 没有 SQL 仍然可以工作,恕我直言,这是首选方式。

标签: spring-boot dependency-injection spring-data flyway


【解决方案1】:

将您的迁移标记为@Component,并将它们放在春季扫描的文件夹中(例如,在您的应用程序包中,而不是在db.migrations 中)。这将确保 @Autowired 可以使用,因为 bean 是由 spring 实例化的。 (db.migrations中的migration会被flyway自动扫描,spring不会实例化。)

然后实现 FlywayConfigurationCustomizer 以通过从 spring 上下文加载迁移来添加迁移:

@Configuration
class FlywayConfiguration implements FlywayConfigurationCustomizer {
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void customize(FluentConfiguration configuration) {
        JavaMigration[] migrationBeans = applicationContext
         .getBeansOfType(JavaMigration.class)
         .values().toArray(new JavaMigration[0]);
        configuration.javaMigrations(migrationBeans);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多