spring和flyway-migrate-before-application context启动

twh00eeo  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(364)

正如标题所示,我正在寻找任何方法来帮助我在加载springs应用程序上下文(确切地说是持久性上下文)之前运行flyway迁移。原因是在应用程序启动时运行的查询很少。这导致我的测试失败,因为正在对尚不存在的数据库表执行查询。我使用h2作为我的测试数据库。现在我只使用flyway core dependency:

<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
    <version>6.5.0</version>
    <scope>test</scope>
</dependency>

我有一个flyway配置类,如下所示:

@Configuration
class FlywayConfig {

    private static final String resourcePath = "classpath:flyway/migrations";
    private static final String sampleDataPath = "classpath:flyway/sample_data";

    @Bean
    Flyway flyway(@Value("${spring.datasource.url}") String dataSource,
                  @Value("${spring.datasource.username}") String username,
                  @Value("${spring.datasource.password}") String password) {

        FluentConfiguration fluentConfiguration = Flyway.configure().dataSource(dataSource, username, password);

        fluentConfiguration.locations(resourcePath, sampleDataPath);

        Flyway flyway = fluentConfiguration.load();

        return flyway;
    }
}

属性在中定义 application.yml ```
spring:
datasource:
username: sa
password: sa
url: 'jdbc:h2:mem:testdb;Mode=Oracle;IGNORE_CATALOGS=TRUE;DB_CLOSE_DELAY=-1;'
platform: h2
h2:
console:
enabled: true
jpa:
show-sql: true

我想要达到的是:1。flyway执行迁移2。Spring上下文加载(按特定顺序)
ua4mk5z4

ua4mk5z41#

我设法通过创造来完成我想要的 DataSource 在配置文件中手动创建对象(不是由spring自动从 application.yml )以及使用 @DependsOnDataSource 对象。通过这种方式,我确保了一旦我在中进行迁移,就可以建立来自应用程序上下文的任何可能的数据库连接 Flyway 豆(顺便说一句,我也调整)。在测试之前,我正在清理和迁移flyway,现在我必须在初始化应用程序上下文bean时这样做。以下是对我有用的代码:

@Configuration
class DatabaseConfig {

    private static final String resourcePath = "classpath:flyway/migrations";
    private static final String sampleDataPath = "classpath:flyway/sample_data";

    private static final String dataSourceUrl = "jdbc:h2:mem:testdb;Mode=Oracle;IGNORE_CATALOGS=TRUE;DB_CLOSE_DELAY=-1;";
    private static final String username = "sa";
    private static final String password = "sa";

    @Bean("flyway")
    public Flyway flyway() {

        FluentConfiguration fluentConfiguration = Flyway.configure().dataSource(dataSourceUrl, username, password);

        fluentConfiguration.locations(resourcePath, sampleDataPath);

        Flyway flyway = fluentConfiguration.load();

        flyway.clean();
        flyway.migrate();

        return flyway;
    }

    @DependsOn("flyway")
    @Bean
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("org.h2.Driver");
        dataSourceBuilder.url(dataSourceUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();
    }
}

这里是 application.yml 文件(我去掉了与数据源相关的记录):

spring:
  h2:
    console:
      enabled: true
  jpa:
    show-sql: true

flyway:
  enabled: false

相关问题