Reputation: 280
I am following akka-java-spring but still don't know how to inject actor within another. For example:
public class Reader extends UntypedConsumerActor {
private ActorRef handler;
public Reader(ActorRef handler) {
this.handler = handler;
}
// ...
}
// Create the handler first
final ActorRef handler = getContext()
.actorOf(SpringExtProvider.get(system).props("Handler"), "handler");
// Now how do I pass the handler above to the Reader ???
final ActorRef reader = ???
Upvotes: 0
Views: 3638
Reputation: 1761
If you want to do this using Spring then the ActorRef would have to be a spring bean. It's possible but imo not very elegant as there isn't a simple way to maintain the supervision hierarchy as well as expose ActorRef's as singleton beans. I played around with this at first but ended up with a lot of top-level actors created which is undesirable. I've found that the most appropriate way for me to combine Spring injection and ActorRef injection into other actors is via message passing as described in the Akka docs.
My Spring service beans are injected via Spring, and my ActorRef's are injected via message passing where required. As ActorRef is quite ambiguous as to what it actually represents you could wrap the ActoRef in a class that also provides a type so the receiving actor can decide what to do with it, very important if they are epxetcing many different ActorRef's to be injected.
Anyway, answering your question, to create a Spring managed ActorRef bean you could do something like the following in a Spring @Configuration class:
@Autowired
private ActorSystem actorSystem;
@Bean(name = "handler")
public ActorRef handler() {
return actorSystem.actorOf(SpringExtProvider.get(system).props("Handler"), "handler");
}
And then in your Spring annotated actor you would have something like:
@Named("Reader")
@Scope("prototype")
public class Reader extends UntypedConsumerActor {
@Autowired
@Qualifier("handler")
private ActorRef handler;
// ...
}
The dependency injection of the "handler" ActorRef will happen when you create the Reader actor using the Spring extension. It's important to remember the ActorRef is a proxy to the Actor.
Upvotes: 4