Search code examples
scalaplayframework-2.2

Scala getResource from Classpath


I have a config file in my src/main/resources folder and I would like to load this, and what I did to do that is:

  println(getClass.getClassLoader.getResource("db.conf"))
  val path = getClass.getClassLoader.getResource("db.conf").getPath
  val DB_CONFIG = ConfigFactory.parseFile(new File(path))
  println(DB_CONFIG)

  // Prepare the MongoDB Connection credentials
  val prepareMongoDBConfig: Option[(String, Int, String, String, String)] = for {

    host   <- Option(DB_CONFIG.getString("database_host"))
    port   <- Option(DB_CONFIG.getInt   ("database_port"))
    user   <- Option(DB_CONFIG.getString("database_user"))
    pass   <- Option(DB_CONFIG.getString("database_pass"))
    dbname <- Option(DB_CONFIG.getString("database_name"))
  } yield (host, port, user, pass, dbname)

Where the db.conf is located under the src/main/resources folder. I package this as a jar and this jar is included as a library in the Play project. When I unit test this, it works fine but when running from within the Play server, I get to see to following:

20:41:10.216 [play-internal-execution-context-1] INFO  play - Application started (Dev)
jar:file:/development/play-server/lib/server-core-1.0-SNAPSHOT.jar!/db.conf
Config(SimpleConfigObject({}))

As it can be seen that the SimpleConfigObject is empty. Why is this?


Solution

  • Oh, I think I see. You are trying to load the resource from the jar as a file, but it isn't a file, it's a path in the jar. It works when you aren't packaged up as a jar because in that case it is a separate file.

    Try ConfigFactory.parseResources("db.conf") or ConfigFactory.parseResourcesAnySyntax("db") perhaps.

    More generic troubleshooting ideas for others who may have a problem like this:

    • Try setting -Dconfig.trace=loads when you launch the prod version and it may have some helpful output on stderr.
    • Unpack the jar with jar xf and be sure it has the expected db.conf in the expected place.