简体   繁体   中英

Akka Http actor injection in trait

I have a object that extends App wherein I create the Actor System and the Actor Materializer and also create an actor under the given actor system.

object QuickstartServer extends App with UserRoutes {

  implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
  implicit val materializer: ActorMaterializer = ActorMaterializer()

  val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")


   lazy val routes: Route = userRoutes
      Http().bindAndHandle(routes, "localhost", 8080)
    }

Now UserRoutes contains all the routes

trait UserRoutes extends JsonSupport {

  implicit def system: ActorSystem
  lazy val log = Logging(system, classOf[UserRoutes])
  def userRegistryActor: ActorRef

  lazy val userRoutes: Route =
    pathPrefix("users") {
      concat(
        pathEnd {
          concat(
            get {
              val users: Future[Users] =
                (userRegistryActor ? GetUsers).mapTo[Users]
//Remaining code 

Now my question is that how is Actor System and the userRegistryActor actor that was created in QuickstartServer injected in the routes file ?

You can find the complete code here https://developer.lightbend.com/guides/akka-http-quickstart-scala/backend-actor.html

At the beginning of the trait, you can see those two declarations :

  implicit def system: ActorSystem
  def userRegistryActor: ActorRef

Those two are abstract declarations in the trait, meaning that implementations of the trait have to provide those two.

That's what's happening in the object, with these two declarations :

 implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
 val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")

A fair share of developers recommend making this kind of implementation more explicit by adding the override keyword, like this :

 override implicit val system: ActorSystem = ActorSystem("helloAkkaHttpServer")
 override val userRegistryActor: ActorRef = system.actorOf(UserRegistryActor.props, "userRegistryActor")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM