Adding custom application settings to Akka’s configuration file

Just added custom application settings to Akka’s configuration file. Retrieving these settings is kind of a mission. This is the statement to retrieve a setting:

getContext().system().settings().config().getString("downloader.download.forceDelete")

Hmmm, putting these statements everywhere in my code does not feel right, does it?

After some Googling I found the Akka extensions page. On this page an Akka extension is described to retrieve the settings in an easy and elegant way.

Here are my code and configuration snippets to help understand the extension mechanism more easily.

Configuration (application.conf):

akka {
	...
}
downloader {
	download {
		forceDelete = true
		resumeDownload = true
	}
}

Code (Settings.scala):

package com.nidkil.downloader.akka.extension

import akka.actor.ExtensionIdProvider
import akka.actor.ExtensionId
import akka.actor.ExtendedActorSystem
import com.typesafe.config.Config
import akka.actor.Extension

class SettingsImpl(config: Config) extends Extension {

  val forceDelete: Boolean = config.getBoolean("downloader.download.forceDelete")
  val resumeDownload: Boolean = config.getBoolean("downloader.download.resumeDownload")
  
}

object Settings extends ExtensionId[SettingsImpl] with ExtensionIdProvider {
  
  override def lookup = Settings
  
  override def createExtension(system: ExtendedActorSystem) =
    new SettingsImpl(system.settings.config)

}

Using the extension:

val system = ActorSystem("Downloader", ConfigFactory.load("application.conf"))
val settings = Settings(system)
println(s"forceDelete=${settings.forceDelete}, resumeDownload=${settings.resumeDownload}")

Makes your code more readible, right? Happy coding 🙂

P.S. to be complete, this is the page where the Akka configuration is documented.

Leave a comment