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

Scala Akka项目src/main/resources下hikari.properties加载失败如何解决

配置加载失败解决方案

1. 修复代码语法/拼写问题

你提供的代码存在两处可直接导致报错的问题:

  • 变量名不匹配:定义的配置路径变量为configPath,调用getResource时错误使用了未定义的hikariConfigPath
  • 路径规则错误:getClass.getResource不加/前缀时,会相对当前类的包路径(你当前类在model.daos包下,会去/model/daos/目录下搜索文件),而非类路径根目录
  • 可选检查:确认代码中所有字符串引号为英文半角引号,避免编译异常

修正后的基础代码如下:

import java.io.FileNotFoundException
import java.util.Properties
import scala.io.Source

val configPath = "hikari.properties"
// 加/前缀表示从类路径根目录查找资源
val url = getClass.getResource(s"/$configPath")
val properties: Properties = new Properties()

if (url != null) {
  val source = Source.fromURL(url)
  properties.load(source.bufferedReader())
  source.close() // 补充关闭资源逻辑,避免资源泄漏
} else {
  println("properties file cannot be loaded at path " + configPath)
  throw new FileNotFoundException("Properties file cannot be loaded")
}

2. 确认项目资源目录配置正确

IDEA 环境

右键src/main/resources目录,选择Mark Directory as -> Resources Root,标记为项目的资源根目录,确保编译时会将目录下的文件复制到类路径。

sbt 环境

确认build.sbt中没有自定义过滤resources目录的配置,sbt默认会自动把src/main/resources下的所有文件同步到编译后的类路径根目录。

验证资源打包结果

编译完成后检查target/scala-[你的Scala版本号]/classes目录下是否存在hikari.properties,如果不存在说明资源没有被正确打包。

3. 可选:替换资源加载方式

如果上述修改后仍报错,可以使用上下文类加载器加载资源,避免当前类加载器的路径限制:

// 替换原url获取逻辑,默认从类路径根目录搜索,不需要加/前缀
val url = Thread.currentThread().getContextClassLoader.getResource(configPath)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:57:04