这里是 Java 8、Guice 4.0 和 Akka 2.3.9。我试图弄清楚如何用 JSR330 风格注释我的演员类@Inject
注释,然后通过 Guice 将它们全部连接起来。
但实际上我读过的每一篇文章(下面的一些例子)要么使用 Scala 代码示例、Guice 的旧版本,要么 Akka 的旧版本:
- 让它崩溃 http://letitcrash.com/post/55958814293/akka-dependency-injection
- 斯卡拉-吉斯 http://www.typesafe.com/activator/template/activator-akka-scala-guice
因此,给出以下 Guice 模块:
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.
}
}
然后我问:我该如何装备MyActorSystemModule
创建实例FizzActor
并正确注射它们与Java (not斯卡拉!)?
请注意:FizzActor
不是我的演员系统中唯一的演员!
Use Creator http://doc.akka.io/japi/akka/2.3.11/akka/actor/Props.html#create(akka.japi.Creator)创造ActorRef
s 在你的 guice 模块的提供者方法中。为了区分不同ActorRef
s,它们是非类型化的,在您的提供者方法和注入点上使用注释,就像您在任何 guice 系统中一样。例如,
在你的 guice 模块中:
@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);
}
}));
}
然后要使用演员服务,注入特定的ActorRef
:
class ClientOfFizzActor {
@Inject
ClientOfFizzActor(@Named("fizzActor") ActorRef fizzActorRef) {..}
}
如果Props.create(..)
Clause 是 Actor 类中的静态工厂方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)