Modern Akka DI with Guice

后端 未结 6 1057
时光取名叫无心
时光取名叫无心 2021-02-13 19:41

Java 8, Guice 4.0 and Akka 2.3.9 here. I am trying to figure out how to annotate my actor classes with JSR330-style @Inject annotations, and then wire them all up v

6条回答
  •  情深已故
    2021-02-13 20:27

    So I have been playing around with Akka and Guice recently alot and I feel that those two don't play too well together.

    What I suggest is you take a similar approach what Play is doing.

    Kutschkem's answer comes closest to that.

    1. use the ActorCreator interface
    2. make sure you have an argumentless Creator. Don't try to do @AssisstedInject in your Creator as this will imply that you will need a new creator for every Actor that you want to create. Personally I believe that initializing this in the actor is better done through messaging.
    3. let the ActorCreator consume an injector such that you can easily create the Actor Object within the Creator.

    Here is a code example using current Akka 2.5. This is the preferred setup we chose for our Akka 2.5 deployment. For brevity I did not provide the Module, but it should be clear from the way the Members are injected, what you want to provide.

    Code:

     class ActorCreator implements Creator
       @Inject
       Injector injector;
       public MyActor create() {
         return injector.getInstance(MyActor.class);
       }
     }
    
     class MyActor extends AbstractActor {
       @Inject
       SomeController object;
    
       @Nullable
       MyDataObject data;
    
       public ReceiveBuilder createReceiveBuilder() {
        return receiveBuilder()
          .match(MyDataObject.class, m -> { /* doInitialize() */ })
          .build(); 
       }
    }
    
    class MyParentActor extends AbstractActor {
       @Inject
       ActorCreator creator;
    
       void createChild() {
         getContext().actorOf(new Props(creator));
       }
    
       void initializeChild(ActorRef child, MyDataObject obj) {
         child.tell(obj);
       }
    }
    

提交回复
热议问题