我在服务器的字段注入上获得空指针异常,该服务器作为akka actor启动.
计划部分:
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类部分:
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()) { .... .... .... }
}
我为dataService获取null.请就此向我提出建议.
谢谢.
解决方法
你得到了NullPointerException,因为Akka正在实例化你的猎犬演员,而不是Guice.您需要让Guice构建您的实例,然后将其传递给Akka,
IndirectActorProducer
可以帮助您实现此目的,例如:
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); } }
请注意,generate()必须在每次调用时创建一个新的Actor实例,它不能返回相同的实例.
然后你可以让Akka通过RetrieverDependencyInjector检索你的actor,例如:
ActorRef myActor = Akka.system().actorOf( Props.create(RetrieverDependencyInjector.class,injector) );
UPDATE
我想你进一步评论,你可以通过提供你想要的Actor作为构造函数参数的类来将RetrieverDependencyInjector变成GenericDependencyInjector,这可能允许你做类似的事情:
Props.create(GenericDependencyInjector.class,injector,Retriever.class)
我没试过这个,但它可能会给你一个起点.