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

使用Gradle Wrapper运行Java应用时找不到application.properties的解决方法

解决Gradle Wrapper运行Java应用时无法加载application.properties的问题

1. 修正配置文件加载代码

绝对不要硬编码相对路径或依赖当前工作目录,改用类加载器从类路径读取资源,这是Java应用加载配置文件的标准方式:

// 正确的加载方式
Properties properties = new Properties();
try (InputStream input = getClass().getClassLoader().getResourceAsStream("application.properties")) {
    if (input == null) {
        throw new FileNotFoundException("无法在类路径中找到application.properties");
    }
    properties.load(input);
} catch (IOException ex) {
    ex.printStackTrace();
}

错误示例:使用new File("src/main/resources/application.properties")会导致运行时依赖当前工作目录,而Gradle Daemon的工作目录并非项目根目录,从而出现路径错误。

2. 验证Gradle资源目录配置

确保build.gradle(或build.gradle.kts)中正确配置了资源目录,Gradle默认会将src/main/resources下的文件打包到类路径,但如果自定义了sourceSets,需确认配置正确:

Groovy DSL示例:

sourceSets {
    main {
        resources {
            srcDirs = ['src/main/resources'] // 确保指向正确的资源目录
        }
    }
}

Kotlin DSL示例:

sourceSets {
    main {
        resources.srcDirs("src/main/resources")
    }
}

3. 清理并重新构建项目

执行以下Gradle Wrapper命令清除缓存并重新构建,避免旧的资源缓存导致路径异常:

./gradlew clean build

之后重新运行应用:

./gradlew run

4. 重启Gradle Daemon(可选)

如果问题仍然存在,停止当前运行的Gradle Daemon以清除可能的缓存问题:

./gradlew --stop

再重新执行运行任务即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:35:26