Reputation: 2982
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)
}
Upvotes: 3
Views: 985
Reputation: 1380
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();
}
}
Upvotes: 2