using guice injection with actor throws null pointer

前端 未结 3 755
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 01:52

I\'m getting null pointer exception on the field injection of a server which is started as an akka actor.

Schedular part:

private Ac         


        
3条回答
  •  情深已故
    2021-01-13 02:26

    You're getting the NullPointerException because Akka is instantiating your Retriever actor and not Guice. You need to get Guice to construct your instance and then pass that to Akka, IndirectActorProducer can help you achieve this, e.g.:

    class RetrieverDependencyInjector implements IndirectActorProducer {
        final Injector injector;
    
        public RetrieverDependencyInjector(Injector injector) {
            this.injector = injector;
        }
    
        @Override
        public Class actorClass() {
            return Retriever.class;
        }
    
        @Override
        public Retriever produce() {
            return injector.getInstance(Retriever.class);
        }
    }
    

    Note that produce() must create a new Actor instance each time it is invoked, it cannot return the same instance.

    You can then get Akka to retrieve your actor through the RetrieverDependencyInjector, e.g.:

    ActorRef myActor = Akka.system().actorOf(
        Props.create(RetrieverDependencyInjector.class, injector)
    );
    

    UPDATE

    I thought about you comment further, you might be able to turn RetrieverDependencyInjector into a GenericDependencyInjector by providing the class of the Actor you want as a constructor parameter, that perhaps will allow you to do something like:

    Props.create(GenericDependencyInjector.class, injector, Retriever.class)
    

    I haven't tried this, but it might give you a starting point.

提交回复
热议问题