如何在Flyway Gradle插件中复用Micronaut的PostgreSQL配置
问题描述
我正尝试使用Flyway的Gradle任务手动执行迁移,已经在Micronaut的application.properties文件中配置好了PostgreSQL连接信息:
datasources.default.url=jdbc:postgresql://localhost:5432/school_staff datasources.default.username=keycloak datasources.default.password=password datasources.default.dialect=POSTGRES datasources.default.driver-class-name=org.postgresql.Driver datasources.default.schema-generate=NONE
当前我的build.gradle.kts配置如下:
buildscript { dependencies { classpath("org.flywaydb:flyway-database-postgresql:11.1.0") } } plugins { id("org.flywaydb.flyway") version "11.0.1" } flyway { url = "jdbc:postgresql://localhost:5432/school_staff" user = "keycloak" password = "password" locations = arrayOf("classpath:db/migration") baselineOnMigrate = true } // Ensure classes are built before migration tasks.named("flywayMigrate").configure { dependsOn(tasks.named("classes")) }
我不想在Gradle配置中重复编写PostgreSQL连接信息,请问如何让Flyway的Gradle配置读取application.properties中的配置?
解决方案
- 加载
application.properties文件:在build.gradle.kts中添加代码读取项目资源目录下的配置文件val appProperties = Properties().apply { val propsFile = file("src/main/resources/application.properties") if (propsFile.exists()) { load(propsFile.inputStream()) } } - 复用配置到Flyway:修改Flyway配置块,替换硬编码的连接参数为properties文件中的值
flyway { url = appProperties.getProperty("datasources.default.url") user = appProperties.getProperty("datasources.default.username") password = appProperties.getProperty("datasources.default.password") locations = arrayOf("classpath:db/migration") baselineOnMigrate = true } - 完整配置示例:整合后的
build.gradle.kts如下buildscript { dependencies { classpath("org.flywaydb:flyway-database-postgresql:11.1.0") } } plugins { id("org.flywaydb.flyway") version "11.0.1" } // 读取Micronaut应用配置 val appProperties = Properties().apply { val propsFile = file("src/main/resources/application.properties") if (propsFile.exists()) { load(propsFile.inputStream()) } } flyway { url = appProperties.getProperty("datasources.default.url") user = appProperties.getProperty("datasources.default.username") password = appProperties.getProperty("datasources.default.password") locations = arrayOf("classpath:db/migration") baselineOnMigrate = true } tasks.named("flywayMigrate").configure { dependsOn(tasks.named("classes")) } - 多环境适配(可选):如果使用多环境配置文件,可通过环境变量或系统属性加载对应配置
val activeEnv = System.getenv("MICRONAUT_ENVIRONMENTS") ?: System.getProperty("micronaut.environments") ?: "dev" val propsFile = file("src/main/resources/application-$activeEnv.properties").takeIf { it.exists() } ?: file("src/main/resources/application.properties") val appProperties = Properties().apply { load(propsFile.inputStream()) }
这样Flyway就能直接复用Micronaut配置中的数据库连接信息,避免重复编写相同配置。
内容的提问来源于stack exchange,提问作者San Jaisy
相关产品推荐
相关产品推荐

