Modern Akka DI with Guice

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

    Unless you are trying to bind UntypedActor to FizzActor, then you can just inject it into other classes as is:

    class SomeOtherClass {
    
        @Inject 
        public SomeOtherClass(FizzActor fizzActor) {
            //do stuff
        }
    }
    

    If you're trying to bind it to the interface, you'll need to specifically do that in the module:

    public class MyActorSystemModule extends AbstractModule {
        @Override
        public void configure() {
            bind(MyService.class).to(MyServiceImpl.class);
            bind(UntypedActor.class).to(FizzActor.class);
        }
    }
    

    Edit:

    What about using @Named to distinguish the UntypedActor, e.g.:

    class SomeOtherClass {
    
        @Inject 
        public SomeOtherClass(@Named("fizzActor")UntypedActor fizzActor, @Named("fooActor") UntypedActor fooActor) {
            //do stuff
        }
    }
    

    Then in your module you could do the akka lookups:

    public class MyActorSystemModule extends AbstractModule {
    
        ActorSystem system = ActorSystem.create("MySystem");
    
        @Override
        public void configure() {
            bind(MyService.class).to(MyServiceImpl.class);
        }
    
        @Provides
        @Named("fizzActor")
        public UntypedActor getFizzActor() {
            return system.actorOf(Props.create(FizzActor.class), "fizzActor");
        }
    
        @Provides
        @Named("fooActor")
        public UntypedActor getFooActor() {
            return system.actorOf(Props.create(FooActor.class), "fooActor");
        }
    }
    

提交回复
热议问题