我正在使用Playframework,我是Akka世界的新手。我试图从父演员创建一个儿童演员。儿童演员依赖于通过guice注入的服务。我无法弄清楚如何实例化这个儿童演员。
class ParentActor extends UntypedActor{
public static Props props = Props.create(ParentActor.class);
@Override
public void preStart() throws Exception{
// The call here fails. I don't know how i should be creating the child actor
childActor = getContext().actorOf(childActor.props);
childActor.tell(Protocol.RUN, self());
}
public void onReceive(Object msg) throws Exception {
if (msg == AggregateProtocol.DONE){
sender().tell(Protocol.RUN, self());
}
}
}
class ChildActor extends UntypedActor{
private ServiceA serviceA;
public static Props props = Props.create(ChildActor.class);
@Inject
public ChildActor(ServiceA serviceA){
this.serviceA = serviceA
}
public void onReceive(Object msg) throws Exception {
if (msg == Protocol.RUN){
serviceA.doWork();
sender().tell(Protocol.DONE, self());
}
}
}
注意:我也尝试过使用工厂和辅助注入的方法,如Play Java akka文档中所述。
我如何让这件事起作用?我也查看了IndirectProducer和Creator方法,但我无法理解文档。
答案 0 :(得分:1)
您可以将服务注入父actor并将其传递给每个子项。
只有父actor使用Guice依赖注入:
class ParentActor extends UntypedActor{
private ServiceA serviceA;
@Inject
public ParentActor(ServiceA serviceA) {
this.serviceA = serviceA;
}
@Override
public void preStart() throws Exception{
// Here pass the reference to serviceA to the child actor
childActor = Akka.system().actorOf(ChildActor.props(serviceA);
childActor.tell(Protocol.RUN, self());
}
public void onReceive(Object msg) throws Exception {
if (msg == AggregateProtocol.DONE){
sender().tell(Protocol.RUN, self());
}
}
}
并且使用props方法创建子actor。
class ChildActor extends UntypedActor{
private ServiceA serviceA;
public static Props props(ServiceA serviceA) {
return Props.create(ChildActor.class, serviceA);
}
// No inject here
public ChildActor(ServiceA serviceA){
this.serviceA = serviceA
}
public void onReceive(Object msg) throws Exception {
if (msg == Protocol.RUN){
serviceA.doWork();
sender().tell(Protocol.DONE, self());
}
}
}
将直接依赖注入到子actor中可能有更好的方法。