现代Akka DI与Guice [英] Modern Akka DI with Guice
问题描述
Java 8,Guice 4.0和Akka 2.3.9。我试图弄清楚如何使用JSR330风格的 @Inject
注释来注释我的actor类,然后通过Guice将它们连接起来。
Java 8, Guice 4.0 and Akka 2.3.9 here. I am trying to figure out how to annotate my actor classes with JSR330-style @Inject
annotations, and then wire them all up via Guice.
但实际上我读过的每篇文章(下面都有一些例子)要么使用Scala代码示例,要么使用犯罪版本的Guice,要么使用犯罪版本的Akka:
But literally every single article I have read (some examples below) either uses Scala code examples, a criminally-old version of Guice, or a criminally-old version of Akka:
- Let It Crash
- Scala-Guice
因此,给定以下Guice模块:
So, given the following Guice module:
public interface MyService {
void doSomething();
}
public class MyServiceImpl implements MyService {
@Override
public void doSomething() {
System.out.println("Something has been done!");
}
}
public class MyActorSystemModule extends AbstractModule {
@Override
public void configure() {
bind(MyService.class).to(MyServiceImpl.class);
}
}
给定 FizzActor
注入 MyService
:
public class FizzActor extends UntypedActor {
private final MyService myService;
@Inject
public FizzActor(MyService myService) {
super();
this.myService = myService;
}
@Override
public void onReceive(Object message) {
// .. Do fizz stuff inside here.
}
}
然后我问:我如何装备up MyActorSystemModule
创建 FizzActor
的实例并正确地将它们注入Java (不是 Scala!)?
Then I ask: How do I rig up MyActorSystemModule
to create instances of FizzActor
and properly inject them with Java (not Scala!)?
请注意: FizzActor
不是唯一的演员在我的演员系统中!
Please note: FizzActor
is not the only actor in my actor system!
推荐答案
使用 Creator 在你的guice的提供者方法中创建 ActorRef
s模块。要区分不同类型的不同 ActorRef
,请在提供者方法和注入点上使用注释,就像使用任何guice系统一样。例如,
Use Creator to create ActorRef
s in provider methods of your guice module. To distinguish between the different ActorRef
s, which are untyped, use annotations on your provider methods and injection points as you would any guice system. For example,
在你的guice模块中:
In your guice module:
@Override
protected void configure() {
bind(ActorSystem.class).toInstance(ActorSystem.apply());
bind(FizzService.class).toInstance(new FizzServiceImpl());
}
@Provides @Singleton @Named("fizzActor")
ActorRef serviceActorRef(final ActorSystem system, final FizzService fizzService) {
return system.actorOf(Props.create(new Creator<Actor>() {
@Override
public Actor create() throws Exception {
return new FizzActor(fizzService);
}
}));
}
然后使用actor服务,注入一个特定的 ActorRef
:
Then to use the actor service, inject a specific ActorRef
:
class ClientOfFizzActor {
@Inject
ClientOfFizzActor(@Named("fizzActor") ActorRef fizzActorRef) {..}
}
如果 Props.create(..)
子句是actor类中的静态工厂方法。
It looks cleaner if the Props.create(..)
clause is a static factory method in your actor class.
这篇关于现代Akka DI与Guice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!