DeejUK
DeejUK

Reputation: 13471

Set name of Spring Boot embedded database

How can I set the name of an embedded database started in a Spring Boot app running in a test?

I'm starting two instances of the same Spring Boot app as part of a test, as they collaborate. They are both correctly starting an HSQL database, but defaulting to a database name of testdb despite being provided different values for spring.datasource.name.

How can I provide different database names, or some other means of isolating the two databases? What is going to be the 'lightest touch'? If I can avoid it, I'd rather control this with properties than adding beans to my test config - the test config classes shouldn't be cluttered up because of this one coarse-grained collaboration test.

Upvotes: 0

Views: 2086

Answers (2)

DeejUK
DeejUK

Reputation: 13471

Gah - setting spring.datasource.name changes the name of the datasource, but not the name of the database.

Setting spring.datasource.url=jdbc:hsql:mem:mydbname does exactly what I need it to. It's a bit crap that I have to hardcode the embedded database implementation, but Spring Boot is using an enum for default values, which would mean a bigger rewrite if it were to try getting the name from a property.

Upvotes: 1

Selim Ok
Selim Ok

Reputation: 1161

You can try it so:

spring.datasource1.name=testdb
spring.datasource2.name=otherdb

And then declare datasource in your ApplicationConfig like this

@Bean
@ConfigurationProperties(prefix="spring.datasource1")
public DataSource dataSource1() {
    ...
}

@Bean
@ConfigurationProperties(prefix="spring.datasource2")
public DataSource dataSource2() {
    ...
}

See official docs for more details: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-configure-a-datasource

Upvotes: 0

Related Questions