Search code examples
scalainitializationserversprayspray-json

Scala spray - init on server statup


I would like to load some data from JSON files when spray server starts-up, How can it be done? How can I write code when server loads like "init" method of Servlets?


Solution

  • Try this:

    object Boot extends App {
        val jsonData: Option[String] = laodJsonFromFile()
        val service = system.actorOf(Props(classOf[YourServiceActor], jsonData), "YourServiceActor")
        implicit val timeout = Timeout(5.seconds)
        // start a new HTTP server on port 80 with our service actor as the handler
        IO(Http) ? Http.Bind(service, 0.0.0.0, 80)
    
        private def laodJsonFromFile() = // some code...
    }
    
    class YourServiceActor(jsonData: Option[String]) extends Actor {
        // ... your code
    }