Mee*_*ary 5 spring database-migration flyway spring-profiles spring-boot
我有两个 Spring 配置文件,dev并test针对开发和测试环境进行了配置。在每个环境中,我h2在开发和postgresql测试中使用不同的数据库。以下是我的每个配置文件的属性文件,其中{vendor}由 Spring Boot 解析h2并分别postgresql根据配置的数据源进行解析。
应用程序-dev.properties
spring.flyway.locations=classpath:db/migration/{vendor}
Run Code Online (Sandbox Code Playgroud)
application-test.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}
Run Code Online (Sandbox Code Playgroud)
dev配置文件的 Flyway 迁移文件位于下test/resources,test配置文件位于下main/resources
当我使用test配置文件运行我的应用程序时它工作正常,它仅在main/resources. 但是,当我使用dev配置文件运行我的单元测试时。我希望它只在src/test/resources/db/migration/h2. 但是 Flyway 正在从中获取迁移文件main/resources并且test/resources两者都导致错误
org.flywaydb.core.api.FlywayException:发现多个版本 1 的迁移
我不明白这种行为。有关如何解决此问题的任何输入?
所以,这就是我如何做到的。
要求:
dev,test和prod。每个环境的数据库:
H2dev环境数据库。postgresqltest环境数据库。postgresqlprod环境数据库。配置
创建 Spring 配置文件dev,test并prod在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}
Run Code Online (Sandbox Code Playgroud)
因为,H2当H2驱动程序在类路径上时,数据库是由 Spring boot 配置的。我们不需要显式配置它。
application-test.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
Run Code Online (Sandbox Code Playgroud)
application-prod.properties
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
Run Code Online (Sandbox Code Playgroud)
如果您会注意到,我没有使用db/migration下src/main/resources放置迁移文件的默认位置。原因很简单,Flyway 会选择该位置下的所有文件,这会导致不同环境下文件之间的版本冲突。例如V2__data_insertion.sql,所有三种环境都存在,如果它们嵌套在db/migration. 由于H2迁移文件属于默认配置文件,因此我将它们保留在默认的 flyway 迁移文件位置。
希望有帮助!!!
这不仅仅与飞行路线有关。
在 Maven 中,它在构建过程中使用两种不同的类路径:
src/main/*)src/test/*(显然),src/main/*因为在测试中您应该能够在编译时访问实际代码。这就是为什么在运行时实际上有 2 个可访问的位置,并且 Flyway 发现了不止一个迁移。
另一个观察:
一般来说,您的生产代码不应包含任何有关测试的内容。但我看到您添加:src/main/resources/application-test.properties此文件将出现在生产工件中,这是错误的。
作为一种解决方法,您可以使用
src/main/resources/application-prod.properties为实际迁移定义位置“X”,而不是:
src/test/resources/application-test.properties为测试迁移定义位置“Y”使用 Profile Test 运行集成测试,您将找不到生产迁移。
| 归档时间: |
|
| 查看次数: |
5300 次 |
| 最近记录: |