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

基于Gradle构建的Java注解处理器无法读取src/main/resources下资源问题

注解处理器读取子项目resources配置方案

问题根因

Gradle 7+默认不会将子项目processResources任务输出的资源目录纳入注解处理器的Filer搜索路径,你此前仅配置了资源编译依赖和输入关联,未将资源路径传递给注解处理器运行环境,因此所有StandardLocation枚举查找都会抛出NoSuchFileException。

解决方案1:通过类路径传递资源目录

第一步:修改子项目build.gradle配置

tasks.withType(JavaCompile) {
    dependsOn processResources
    // 将资源输出目录追加到注解处理器的类路径
    options.compilerArgs += [
        "--processor-path",
        configurations.annotationProcessor.asPath + File.pathSeparator + layout.buildDirectory.dir("resources/main").get().asFile.absolutePath
    ]
    // 配置资源目录为编译输入,资源变更时自动触发重编译
    inputs.dir(layout.buildDirectory.dir("resources/main"))
}

第二步:注解处理器中读取文件

// 第二个参数留空,第三个参数填写资源文件的完整相对路径
FileObject fileObj = processingEnv.getFiler().getResource(StandardLocation.CLASS_PATH, "", "sub/file.txt");
try (InputStream inputStream = fileObj.openInputStream()) {
    // 此处编写读取文件内容的逻辑
} catch (IOException e) {
    // 异常处理逻辑
}

解决方案2:直接传递资源目录参数(更稳定)

如果方案1存在类路径冲突问题,可以直接将资源目录作为自定义参数传给注解处理器:

第一步:修改子项目build.gradle配置

tasks.withType(JavaCompile) {
    dependsOn processResources
    // 传递资源目录给注解处理器
    def resourcesOutputPath = layout.buildDirectory.dir("resources/main").get().asFile.absolutePath
    options.compilerArgs += "-Aproject.resources.dir=${resourcesOutputPath}"
}

第二步:注解处理器中读取文件

@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);
    // 获取传入的资源目录参数
    String resourcesDir = processingEnv.getOptions().get("project.resources.dir");
    // 拼接目标文件路径直接读取
    File configFile = new File(resourcesDir, "sub/file.txt");
    // 此处编写读取configFile的逻辑即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:27:04