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

后端 未结 5 1103
青春惊慌失措
青春惊慌失措 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条回答
  •  梦毁少年i
    2021-01-05 07:18

    There's a caveat that hasn't been considered in the other answers. What you need to be aware of is that starting a server is a transient dependency on your DataSource bean. This is due to the DataSource only needing a network connection, not a bean relationship.

    The problem this causes is that spring-boot will not know about the h2 database needing to be fired up before creating the DataSource, so you could end up with a connection exception on application startup.

    With the spring-framework this isn't a problem as you put the DB server startup in the root config with the database as a child. With spring boot AFAIK there's only a single context.

    To get around this what you can do is create an Optional dependency on the data-source. The reason for Optional is you may not always start the server (configuration parameter) for which you may have a production DB.

    @Bean(destroyMethod = "close")
    public DataSource dataSource(Optional h2Server) throws PropertyVetoException {
        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(env.getProperty("db.driver"));
        ds.setJdbcUrl(env.getProperty("db.url"));
        ds.setUsername(env.getProperty("db.user"));
        ds.setPassword(env.getProperty("db.pass"));
        return ds;
    }
    

提交回复
热议问题