Gradle KTS中如何从依赖Jar引用GraphQL-Kotlin的schemaFile
问题描述
将可正常运行的Maven项目迁移至Gradle时,配置GraphQL-Kotlin从Jar依赖加载schema文件遇到问题。Gradle KTS中指定schemaFile相对路径后,任务报错文件不存在,但相同逻辑在Maven中可正常运行,需实现从com.company.schemasgraphql:some-service:1.1.0依赖中加载graphql/schemas/some-service/schema.graphql文件。
当前Gradle配置
plugins { kotlin("jvm") version "1.9.0" ... id("com.expediagroup.graphql") version "6.5.3" } dependencies { compileOnly("com.company.schemasgraphql:some-service:1.1.0") ... } graphql { client { packageName = "com.company.someservice" schemaFile = file("graphql/schemas/some-service/schema.graphql") queryFileDirectory = "${project.projectDir}/src/main/resources/queries" allowDeprecatedFields = true } }
报错信息
FAILURE: Build failed with an exception. * What went wrong: A problem was found with the configuration of task ':some-service:graphqlGenerateClient' (type 'GraphQLGenerateClientTask'). - In plugin 'com.expediagroup.graphql' type 'com.expediagroup.graphql.plugin.gradle.tasks.GraphQLGenerateClientTask' property 'schemaFile' specifies file '(...)graphql/schemas/some-service/schema.graphql' which doesn't exist. Reason: An input file was expected to be present but it doesn't exist.
可用Maven配置
<plugin> <groupId>com.expediagroup</groupId> <artifactId>graphql-kotlin-maven-plugin</artifactId> <version>${graphql-kotlin.version}</version> <dependencies> <dependency> <groupId>com.company.schemasgraphql</groupId> <artifactId>some-service</artifactId> <version>${some-service.version}</version> </dependency> </dependencies> <executions> <execution> <id>generate-some-service-client</id> <goals> <goal>generate-client</goal> </goals> <configuration> <packageName>com.company.someservice</packageName> <schemaFile>graphql/schemas/some-service/schema.graphql</schemaFile> <queryFileDirectory> ${project.basedir}/src/main/resources/queries </queryFileDirectory> <allowDeprecatedFields>true</allowDeprecatedFields> </configuration> </execution> </executions> </plugin>
解决方案
Maven插件会自动从自身依赖中查找schema文件,但Gradle插件的schemaFile默认仅在项目本地文件系统查找。需调整以下两点:
- 将schema依赖添加到插件类路径
Gradle插件不会自动使用项目的compileOnly依赖,需把schema Jar添加到GraphQL插件的类路径中:
plugins { kotlin("jvm") version "1.9.0" ... id("com.expediagroup.graphql") version "6.5.3" } // 配置插件类路径,引入schema依赖 buildscript { dependencies { classpath("com.company.schemasgraphql:some-service:1.1.0") } } dependencies { compileOnly("com.company.schemasgraphql:some-service:1.1.0") ... }
- 通过类路径加载schema文件
放弃使用file()方法(仅查本地文件),改用resources.text.fromClasspath()从插件类路径读取schema资源:
graphql { client { packageName = "com.company.someservice" // 从类路径加载Jar内的schema文件 schemaFile = resources.text.fromClasspath("graphql/schemas/some-service/schema.graphql").asFile queryFileDirectory = file("src/main/resources/queries") // 用file()替代字符串拼接更规范 allowDeprecatedFields = true } }
额外验证:可通过jar tf some-service-1.1.0.jar命令确认Jar包中确实包含graphql/schemas/some-service/schema.graphql资源文件。
内容的提问来源于stack exchange,提问作者Mike Minicki
相关产品推荐
相关产品推荐

