Home » JVM Languages » Scala » Alternating between Spray-servlet and Spray-can

About Arthur Arts

Arthur Arts
Arthur Arts is an experienced Enterprise Java software engineer and hands-on Agile Coach and Scrum Master. He has a strong focus on agile engineering principles and practices and loves to share his knowledge and learn from others. He has his own company Coded Value, is a passionate photographer and writes for agilearts.nl.

Alternating between Spray-servlet and Spray-can

On a server you may want to deploy your application as a war. How to build a war with spray-servlet. Locally it’s easiest to run without an application server.

We include both the spray-servlet and spray-can dependencies:

name := "sprayApiExample"

version := "1.0"

scalaVersion := "2.11.6"

libraryDependencies ++= {
  val akkaV = "2.3.9"
  val sprayV = "1.3.3"
  Seq(
    "io.spray"            %%  "spray-can"     % sprayV,
    "io.spray"            %%  "spray-servlet" % sprayV,
    "io.spray"            %%  "spray-routing" % sprayV,
    "io.spray"            %%  "spray-json"    % "1.3.1", //has not been updated yet
    "com.typesafe.akka"   %%  "akka-actor"    % akkaV
  )
}

//This adds tomcat dependencies, you can also use jetty()
tomcat()

We make a trait with all the common functionality. We extend both SprayApiServlet and SprayApiCan from it.

import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
import spray.servlet.WebBoot
import scala.concurrent.duration._

trait SprayApi {
  implicit val system = ActorSystem("SprayApiApp")
  val apiActor = system.actorOf(Props[ApiActor], "apiActor")
}

//for use with spray-servlet
class SprayApiServlet extends WebBoot with SprayApi {
  override val serviceActor = apiActor
}

//for use with spray-can
object SprayApiCan extends App with SprayApi {
  implicit val timeout = Timeout(5.seconds)
  IO(Http) ? Http.Bind(apiActor, interface = "localhost", port = 8080)
}
  • You can see the whole example here.
Reference: Alternating between Spray-servlet and Spray-can from our JCG partner Tammo Sminia at the JDriven blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments