简体   繁体   中英

Dynamically configure spring boot h2 database

I want to dynamically configure the H2 database that comes with my spring boot application. All the examples I have seen talk about adding or changing the application.properties file.

What I want to do is something like this which is executed at boot time (hence dynamically ):

// pseudo code
if environment variable or argument defined (ex: --h2.location = /tmp.foo.txt)
{
  define url spring.datasource.url=jdbc:h2:file:<h2.location>
  keep all other default values
}
else
{
  use default spring.datasource.url (memory)
}

You can get that dynamically calculated at boot time with a single line in the application.properties:

spring.datasource.url=${h2.file.datasource:jdbc:h2:mem:testdb} 

Where your argument variable would be the datasource url: h2.file.datasource=jdbc:h2:file:./tmp.foo.txt


If you want more control of the datasource creation just write a configuration component with a method that returns a datasource:

@Configuration
public class H2DatasurceConfiguration {

    @Value("${h2.location:#{null}}")
    private String h2Location;

    @Bean
    public DataSource getDataSource() {

        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();

        if (h2Location != null) {
            dataSourceBuilder.url("jdbc:h2:file:" + h2Location);
            // Additional datasource configuration for file db
        } else {
            dataSourceBuilder.url("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
            // Additional datasource configuration for in memmory db
        }
        return dataSourceBuilder.build();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM