【问题标题】:How to instantiate child actors when their constructor args are dependency injected?当他们的构造函数参数被依赖注入时如何实例化子演员?
【发布时间】:2016-01-25 02:22:42
【问题描述】:

我正在使用 Playframework,而且我是 Akka 世界的新手。我正在尝试从父演员创建一个子演员。子actor依赖于通过guice注入的服务。我无法弄清楚如何实例化这个子actor。

    class ParentActor extends UntypedActor{

        public static Props props = Props.create(ParentActor.class);

        @Override
        public void preStart() throws Exception{
          // The call here fails. I don't know how i should be creating the child actor 
          childActor = getContext().actorOf(childActor.props);
          childActor.tell(Protocol.RUN, self());
        }

        public void onReceive(Object msg) throws Exception {
           if (msg == AggregateProtocol.DONE){
              sender().tell(Protocol.RUN, self());
           }
        } 

    }

    class ChildActor extends UntypedActor{

       private ServiceA serviceA;

       public static Props props = Props.create(ChildActor.class);

       @Inject
       public ChildActor(ServiceA serviceA){
           this.serviceA = serviceA
       }

        public void onReceive(Object msg) throws Exception {
           if (msg == Protocol.RUN){
              serviceA.doWork();
              sender().tell(Protocol.DONE, self());
           }
        } 

   }

注意:我还尝试了使用工厂和辅助注入的方法,如 Play Java akka 文档中所述。

我如何让这个东西工作?我也看过 IndirectProducer 和 Creator 方法,但我无法很好地理解文档。

【问题讨论】:

标签: playframework akka playframework-2.4


【解决方案1】:

您可以将服务注入到父actor中并将其传递给每个子actor。

只有父actor使用Guice依赖注入:

class ParentActor extends UntypedActor{

    private ServiceA serviceA;

    @Inject
    public ParentActor(ServiceA serviceA) {
      this.serviceA = serviceA;
    }

    @Override
    public void preStart() throws Exception{
      // Here pass the reference to serviceA to the child actor
      childActor = Akka.system().actorOf(ChildActor.props(serviceA);
      childActor.tell(Protocol.RUN, self());
    }

    public void onReceive(Object msg) throws Exception {
       if (msg == AggregateProtocol.DONE){
          sender().tell(Protocol.RUN, self());
       }
    } 

}

子actor像往常一样使用 props 方法创建。

class ChildActor extends UntypedActor{

   private ServiceA serviceA;

   public static Props props(ServiceA serviceA) {
     return Props.create(ChildActor.class, serviceA);
   }

   // No inject here
   public ChildActor(ServiceA serviceA){
       this.serviceA = serviceA
   }

   public void onReceive(Object msg) throws Exception {
      if (msg == Protocol.RUN){
          serviceA.doWork();
          sender().tell(Protocol.DONE, self());
      }
   } 

}

可能有更好的方法直接将依赖注入到子actor中。

【讨论】:

  • 谢谢克里斯。我已经尝试过你的方法并且它有效。但我认为这在涉及深度嵌套的演员层次结构时并不理想。
  • 我同意。直接注入会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 2023-03-27
  • 2012-08-28
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多