You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Gradle时Service Loader无法找到提供者,Maven则正常

解决Gradle下Querydsl APT无法加载META-INF/services扩展的问题

问题根源

Gradle的Java编译任务默认不会将依赖包中的META-INF/services资源文件自动加入APT处理器的类路径,导致Querydsl的Service Loader无法发现querydsl-ext-apt中的扩展提供者,最终只生成原生QClass。

解决方案

1. 确保依赖配置正确

首先确认querydsl-ext-apt已被添加为annotationProcessor范围的依赖,这样Gradle才会在APT阶段加载它:

// Groovy DSL
dependencies {
    annotationProcessor 'com.querydsl:querydsl-apt:5.0.0' // 替换为你的Querydsl版本
    annotationProcessor 'io.github.bigbang4u2:querydsl-ext-apt:1.0.0' // 替换为你仓库的依赖坐标
    implementation 'com.querydsl:querydsl-jpa:5.0.0'
    // 其他Hibernate Types相关依赖
}
// Kotlin DSL
dependencies {
    annotationProcessor("com.querydsl:querydsl-apt:5.0.0")
    annotationProcessor("io.github.bigbang4u2:querydsl-ext-apt:1.0.0")
    implementation("com.querydsl:querydsl-jpa:5.0.0")
}

2. 配置APT类路径包含资源文件

修改Java编译任务,将运行时类路径加入APT的类路径,确保META-INF/services文件能被Service Loader读取:

// Groovy DSL
tasks.withType(JavaCompile) {
    options.classpath += sourceSets.main.runtimeClasspath
}
// Kotlin DSL
tasks.withType<JavaCompile>().configureEach {
    options.classpath += sourceSets.main.get().runtimeClasspath
}

3. 手动指定Querydsl扩展(可选)

如果上述配置仍不生效,可以直接在编译参数中指定扩展类,绕过Service Loader的自动扫描:

// Groovy DSL
tasks.withType(JavaCompile) {
    options.compilerArgs += [
        '-Aquerydsl.extensions=com.your.package.YourExtensionClass' // 替换为实际的扩展类全限定名
    ]
}
// Kotlin DSL
tasks.withType<JavaCompile>().configureEach {
    options.compilerArgs.add("-Aquerydsl.extensions=com.your.package.YourExtensionClass")
}

4. 配合Querydsl插件配置(若使用)

如果你用了第三方Querydsl Gradle插件,确保生成目录配置正确,避免生成的QClass被覆盖:

// Groovy DSL
querydsl {
    jpa = true
    querydslSourcesDir = file('src/main/generated')
}
// Kotlin DSL
querydsl {
    jpa.set(true)
    querydslSourcesDir.set(file("src/main/generated"))
}

验证步骤

  1. 执行./gradlew clean compileJava清理并重新编译
  2. 查看生成的QClass,检查是否包含你扩展中的字段/方法
  3. 若仍有问题,可开启Gradle的调试日志./gradlew clean compileJava --debug,搜索ServiceLoader相关日志,确认是否加载到了你的扩展提供者

内容的提问来源于stack exchange,提问作者big

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:43:28