如何在 SpringBoot 应用程序中迁移之前 运行 flyway:clean?

How to run flyway:clean before migrations in a SpringBoot app?

我正在使用 Springboot 和 Flyway。迁移工作正常,但我希望能够在应用程序上下文加载 test 配置文件时执行 clean flyway 命令。

如果活动配置文件是 test,是否可以配置 SpringBoot 执行 clean 然后 migrate

您可以像这样覆盖 Flyway 自动配置:

@Bean
@Profile("test")
public Flyway flyway(DataSource theDataSource) {
    Flyway flyway = new Flyway();
    flyway.setDataSource(theDataSource);
    flyway.setLocations("classpath:db/migration");
    flyway.clean();
    flyway.migrate();

    return flyway;
}

在SpringBoot 1.3(当前版本为1.3.0.M1,计划于9月正式发布)中,您可以使用FlywayMigrationStrategy bean来定义您想要运行的操作:

@Bean
@Profile("test")
public FlywayMigrationStrategy cleanMigrateStrategy() {
    FlywayMigrationStrategy strategy = new FlywayMigrationStrategy() {
        @Override
        public void migrate(Flyway flyway) {
            flyway.clean();
            flyway.migrate();
        }
    };

    return strategy;
}

在更新的 spring 引导版本(例如 2.0.2)中,如果您想使用 clean,则可以使用 属性 spring.flyway.clean-on-validation-error,因为 sql 个文件