Search code examples
hocon

HOCON: multiple reference.conf resolution issue


I have multi-module project under SBT.

Project A (library) has reference.conf file with A's configuration parameters. Project A depends on akka-actor library, which ships with its own reference.conf file. Project A redefines some akka's parameters in own reference.conf.

Project B depends on A.

When I call ConfigFactory.load() in B, I'm getting wrong order of reference.confs merging. It first takes A's config, then applies akka-actor's config over it. Eventually, I'm getting initial akka-actor's configuration.

How can I fix it? I need to get akka-actor's config loaded first, then my A's config should be applied over it.


Solution

  • Ok, looks like I've found the answer in sources of ConfigFactory.

    All the reference.conf is being loaded through ClassLoader.getResources. It returns java.util.Enumeration[URL]. The order of URLs in this enum is the answer to the question. So all you need to do: ensure the order of your reference.conf resources in this enumeration properly arranged.

    Here is an example of how to do that. First, create your own version of ClassLoader by overriding getResources method:

    import scala.collection.JavaConverters._
    
    class CustomClassLoader(loader: ClassLoader) extends ClassLoader(loader){
        override def getResources(name: String): util.Enumeration[URL] = {
            val resources = super.getResources(name).asScala.toList
            // arrange resources as you wish here
            java.util.Collections.enumeration(resources.asJava)
        }
    }
    

    Last, call load method of ConfigFactory with your CustomClassLoader instance.