我有两个 Spring 配置文件dev
and test
配置为开发和测试环境。在每个环境中我使用不同的数据库即h2
在开发和postgresql
在测试中。以下是每个配置文件的我的属性文件,其中{vendor}
由 spring boot 解决h2
and postgresql
分别根据配置的数据源。
应用程序-dev.properties
spring.flyway.locations=classpath:db/migration/{vendor}
应用程序测试.properties
#Data source
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
#Flyway
spring.flyway.check-location=false
spring.flyway.locations=classpath:/db/migration/test/{vendor}
Flyway 迁移文件dev
个人资料在下面test/resources
并为test
个人资料下main/resources
当我运行我的应用程序时,这工作正常test
配置文件,它只在下面选择迁移文件main/resources
。但是,当我使用运行单元测试时dev
轮廓。我希望它只选择下面的文件src/test/resources/db/migration/h2
。但 Flyway 正在从以下位置获取迁移文件main/resources
and test/resources
两者都会导致错误
org.flywaydb.core.api.FlywayException:发现多个版本 1 的迁移
我不明白这种行为。有关如何解决此问题的任何意见?
所以,这就是我的做法。
要求:
- 使用 Spring 配置文件为不同环境配置应用程序,即
dev
, test
and prod
.
- 使用 Spring 配置文件根据环境加载 Flyway 迁移文件。
每个环境的数据库:
-
H2
数据库为dev
环境。
-
postgresql
数据库为test
环境。
-
postgresql
数据库为prod
环境。
配置
-
创建 Spring 配置文件dev
, test
and prod
in pom.xml.
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
</profile>
<profile>
<id>prod</id>
</profile>
</profiles>
为每个配置文件创建属性文件
应用程序-dev.properties
spring.flyway.locations=classpath:db/migration/{vendor}
Since, H2
数据库由Spring boot配置时H2驱动程序位于类路径上。我们不需要显式地配置它。
应用程序测试.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/db_test
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.flyway.locations=/db/{vendor}/common,/db/{vendor}/test
应用程序产品属性
spring.datasource.url=jdbc:postgresql://localhost:5432/db_prod
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.flyway.locations=/db/{vendor}/common,/db/{vendor}/prod
- Flyway 迁移文件位置。
如果你注意到的话,我没有使用过db/migration
under src/main/resources
放置迁移文件,这是默认位置。原因很简单,Flyway 会选择此位置下的所有文件,这会导致不同环境的文件之间存在版本冲突。例如V2__data_insertion.sql
存在于所有三个环境中,如果它们嵌套在下面,则这将不起作用db/migration
。自从,H2
迁移文件与默认配置文件相关,我已将它们留在默认的 Flyway 迁移文件位置。
希望有帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)