java - 如何在 Spring Boot 应用程序中使用 Flyway 启动 H2 db TCP 服务器

标签 java spring-boot flyway h2db

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

所以我有这样的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 数据库服务器的配置类。

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

最佳答案

我找到了解决方案:

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

关于java - 如何在 Spring Boot 应用程序中使用 Flyway 启动 H2 db TCP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45620327/

相关文章:

java - 我们可以停止构造函数的运行吗?

java - 测试中的自定义注释

spring-boot - Swagger UI 试试吧!不适用于 Kubernetes 入口

spring - RestTemplate 与 OpenFeign。 OpenFeign 它只是 RestTemplate 的可能替代方案还是存在必须使用它的用例?

postgresql - Postgres/Flyway : How can I wrap long constant strings in sql file?

spring - 我应该能够为 Flyway bean 的 init 方法使用 Spring 占位符吗?

sql-server - 如何使用Flyway命令行客户端和flyway.conf迁移多个数据库?

java - 如何阻止 repaint() 方法闪烁

java - 是 hibernate bug吗?

java - 如何在 IntelliJ IDEA 中执行 Boolean To Enum 重构?