1

我将 Spring Boot 和 H2 db 与 Flyway 一起使用,我想在我的应用程序启动时启动 H2 db tcp 服务器(用 Spring Boot 编写)。

所以我有这样的application.properties文件。

db.port=9090
spring.datasource.url=jdbc:h2:tcp://localhost:${db.port}/./database/ifin-relax
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver

flyway.baseline-on-migrate=true
flyway.url=jdbc:h2:tcp://localhost:${db.port}/./database/ifin-relax
flyway.table=SCHEMA_VERSION
flyway.user=sa
flyway.password=password

而且我还有以下用于 h2 db 服务器的配置类。

@Configuration
public class H2DBServerConfiguration {

    @Value("${db.port}")
    private String h2DbPort;

    @Bean
    public Server server() throws SQLException {
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", h2DbPort).start();
    }
}

但是当我运行应用程序时它会失败并出现异常

Error creating bean with name 'flywayInitializer' defined in class path resource

似乎 flyway 甚至在 H2 的 TCP 服务器被实例化之前就尝试应用迁移。所以问题是如何推迟飞行路线迁移,直到数据库服务器启动?

4

1 回答 1

2

我找到了一个解决方案:

@Configuration
public class H2ServerConfiguration {

    @Value("${db.port}")
    private String h2TcpPort;

   /**
    * TCP connection to connect with SQL clients to the embedded h2 database.
    *
    * @see Server
    * @throws SQLException if something went wrong during startup the server.
    * @return h2 db Server
    */
    @Bean
    public Server server() throws SQLException {
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", h2TcpPort).start();
    }

    /**
     * @return FlywayMigrationStrategy the strategy for migration.
     */
     @Bean
     @DependsOn("server")
     public FlywayMigrationStrategy flywayMigrationStrategy() {
         return Flyway::migrate;
     }
}
于 2017-08-12T17:14:07.883 回答