Modern Akka DI with Guice

后端 未结 6 1038
时光取名叫无心
时光取名叫无心 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:21

    Use Creator to create ActorRefs in provider methods of your guice module. To distinguish between the different ActorRefs, which are untyped, use annotations on your provider methods and injection points as you would any guice system. For example,

    In your guice module:

    @Override
    protected void configure() {
        bind(ActorSystem.class).toInstance(ActorSystem.apply());
        bind(FizzService.class).toInstance(new FizzServiceImpl());
    }
    
    @Provides @Singleton @Named("fizzActor")
    ActorRef serviceActorRef(final ActorSystem system, final FizzService fizzService) {
        return system.actorOf(Props.create(new Creator() {
            @Override
            public Actor create() throws Exception {
                return new FizzActor(fizzService);
            }
        }));
    }
    

    Then to use the actor service, inject a specific ActorRef:

    class ClientOfFizzActor {
        @Inject
        ClientOfFizzActor(@Named("fizzActor") ActorRef fizzActorRef) {..}
    }
    

    It looks cleaner if the Props.create(..) clause is a static factory method in your actor class.

提交回复
热议问题