I use Spring Boot and H2 db with Flyway, and I want to start the H2 db tcp server upon start of my application (written in Spring Boot).
So I have such application.properties file.
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
And also I have the following configuration class for 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();
}
}
But when I run the application it fails with exception
Error creating bean with name 'flywayInitializer' defined in class path resource
It seems that flyway tries to apply migrations even before H2's TCP server was instantiated. So the question is how to postpone flyway migrations until the DB Server is started?
I found a solution:
@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;
}
}