如何在Spring Boot应用程序和flyway中启动H2 db TCP服务器

时间:2017-08-10 17:46:09

标签: java spring-boot flyway h2db

我在Flyway中使用Spring Boot和H2 db,我想在启动应用程序时启动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 server的以下配置类。

@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服务器实例化之前应用迁移。那么问题是如何在数据库服务器启动之前推迟飞路迁移?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

@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;
     }
}