gpt4 book ai didi

java - 访问模块内的 Play 2 ActorSystem 引用

转载 作者:行者123 更新时间:2023-11-30 02:18:30 24 4
gpt4 key购买 nike

根据documentation对于 Play 2.6:

The deprecated static methods play.libs.Akka.system and play.api.libs.concurrent.Akka.system were removed. Use dependency injection to get an instance of ActorSystem and access to the actor system.

该文档提供了一个使用 POJO 注释的示例,但是在模块中使用时该语法似乎不起作用...

我们的类定义如下所示:

public class SomeMagicalModule extends AbstractModule implements AkkaGuiceSupport {...}

1) 尝试在类成员上使用 @Inject 会产生 NULL 引用:

    @Inject
protected ActorSystem system;

2) 尝试在模块的构造函数上使用 @Inject 会抛出play.api.PlayException:没有有效的构造函数:

    public SomeMagicalModule (@Inject AkkaSystem system) {...}

还有其他途径获得 AkkaSystem,还是我们错过了一些简单的东西?

TIA。

最佳答案

您可以使用@Provides

When you need code to create an object, use an @Provides method. The method must be defined within a module, and it must have an @Provides annotation. The method's return type is the bound type. Whenever the injector needs an instance of that type, it will invoke the method. If the @Provides method has a binding annotation like @PayPal or @Named("Checkout"), Guice binds the annotated type. Dependencies can be passed in as parameters to the method. The injector will exercise the bindings for each of these before invoking the method.

@Provides
CreditCardProcessor providePayPalCreditCardProcessor(@Named("PayPal API key") String apiKey) {
PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
processor.setApiKey(apiKey);
return processor;
}

但是,您应该考虑到

Whenever the injector needs an instance of that type, it will invoke the method

因此,如果您有两个依赖于 Provided 组件的组件(在本例中为 CreditCardProcessor),您最终将得到该组件的 2 个实例,因为Guice 注入(inject)器每次需要注入(inject)该类型的实例时都会调用该方法。

Scopes对此提供解决方案,您必须添加 @Singleton 注释。

@Provides
@Singleton
CreditCardProcessor providePayPalCreditCardProcessor(@Named("PayPal API key") String apiKey) {
PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
processor.setApiKey(apiKey);
return processor;
}

就你的情况而言,它将是

public class SomeMagicalModule extends AbstractModule implements AkkaGuiceSupport {

@Provides
@Singleton
@Named("some-actor")
ActorRef createActor(system: ActorSystem){
system.actorOf(...)
}
}

感谢 codejanovic,请参阅 his answer .

无论如何,如果你想要引用 ActorSystem 来创建 Actor,你应该使用 AkkaGuiceSupport (我看到您已经将其添加到您的模块中,但您似乎没有使用它)。

关于java - 访问模块内的 Play 2 ActorSystem 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47556185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com