How to start H2 TCP server on Spring Boot application startup?

后端 未结 5 1113
青春惊慌失措
青春惊慌失措 2021-01-05 06:44

I\'m able to start the H2 TCP server (database in a file) when running app as Spring Boot app by adding following line into the SpringBootServletInitializer main method:

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-05 07:00

    This solution works for me. It starts the H2 server if the app runs as Spring Boot app and also if it runs on Tomcat. Creating H2 server as a bean did not work because the Flyway bean was created earlier and failed on "Connection refused".

    @SpringBootApplication
    @Log
    public class NatiaApplication extends SpringBootServletInitializer {
    
        public static void main(String[] args) {
            startH2Server();
            SpringApplication.run(NatiaApplication.class, args);
        }
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            startH2Server();
            return application.sources(NatiaApplication.class);
        }
    
        private static void startH2Server() {
            try {
                Server h2Server = Server.createTcpServer().start();
                if (h2Server.isRunning(true)) {
                    log.info("H2 server was started and is running.");
                } else {
                    throw new RuntimeException("Could not start H2 server.");
                }
            } catch (SQLException e) {
                throw new RuntimeException("Failed to start H2 server: ", e);
            }
        }
    }
    

提交回复
热议问题