设置Spring Boot嵌入式数据库的名称



如何设置在测试中运行的Spring Boot应用程序中启动的嵌入式数据库的名称?

作为测试的一部分,我将启动同一个Spring Boot应用程序的两个实例,因为它们正在协作。它们都正确地启动了HSQL数据库,但默认为testdb的数据库名称,尽管为spring.datasource.name提供了不同的值。

我如何提供不同的数据库名称,或其他隔离两个数据库的方法?什么将是"最轻的触摸"?如果可以避免的话,我宁愿用属性来控制它,也不愿在我的测试配置中添加bean——测试配置类不应该因为这一个粗粒度的协作测试而混乱不堪。

Gah-设置spring.datasource.name会更改数据源的名称,但不会更改数据库的名称。

设置spring.datasource.url=jdbc:hsql:mem:mydbname正是我所需要的。我必须对嵌入式数据库实现进行硬编码,这有点垃圾,但Spring Boot使用枚举作为默认值,这意味着如果它试图从属性中获取名称,则需要进行更大的重写。

您可以这样尝试:

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

然后在ApplicationConfig中声明数据源,如下

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

有关更多详细信息,请参阅官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-配置数据源

相关内容

最新更新