There is a caution that has not been addressed in other answers. What you need to know is that starting the server is a transient dependency on your DataSource bean. This is because the DataSource only needs a network connection, not a bean.
The problem is that spring-boot will not be aware of the need to start the h2 database before creating the DataSource , so when you start the application you can get a connection exception.
When using spring -foundation, this is not a problem, since you start the database server launch in RootConfig with the database as a child. When using spring AFAIK boot, there is only one context.
To get around this, you can create an Optional<Server> dependency on the data source. Optional reason is that you cannot always start the server (configuration parameter), for which you may have a production database.
@Bean(destroyMethod = "close") public DataSource dataSource(Optional<Server> 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; }
source share