Java – use Guice injection and actor to throw null pointers

I get a null pointer exception on the field injection of the server, which starts as an akka actor

Plan part:

private ActorRef myActor = Akka.system().actorOf(
        new Props(Retreiver.class));

@Override
public void onStart(Application app) {
    log.info("Starting schedular.....!");
    Akka.system()
            .scheduler()
            .schedule(Duration.create(0,TimeUnit.MILLISECONDS),Duration.create(30,TimeUnit.MINUTES),myActor,"tick",Akka.system().dispatcher());

}

Retreiver class part:

public class Retreiver extends UntypedActor {

private Logger.ALogger log = Logger.of(Retreiver .class);

@Inject
private myDataService dataService;

@Override
public void onReceive(Object arg0) throws Exception {

    if (0 != dataService.getDataCount()) {
    ....
    ....
    ....
    }

}

I get null for DataService Please advise me on this

thank you.

Solution

You got a NullPointerException because akka is instantiating your hound actor instead of Guice You need Guice to build your instance and then pass it to akka. Indirectactor producer can help you achieve this goal, for example:

class RetrieverDependencyInjector implements IndirectActorProducer {
    final Injector injector;

    public RetrieverDependencyInjector(Injector injector) {
        this.injector = injector;
    }

    @Override
    public Class<? extends Actor> actorClass() {
        return Retriever.class;
    }

    @Override
    public Retriever produce() {
        return injector.getInstance(Retriever.class);
    }
}

Note that generate () must create a new actor instance every time it is called, and it cannot return the same instance

Then you can ask akka to retrieve your actor through retrieveredependencyinjector, for example:

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

UPDATE

I want you to comment further that you can turn retrieveredependencyinjector into genericdependencyinjector by providing the class with the actor you want as the constructor parameter, which may allow you to do similar things:

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

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>