我正在將Play 2.3.x應用程序遷移到Play 2.5.x,並且在使用依賴注入時遇到了一些問題。如何正確使用DI來注入Play控制器的構造函數?
在2.3中,我有一個特性HasRemoteActor
,控制器會根據配置混合引用一些遠程參與者。由於這需要應用程序的配置對象,現在要求它變成一個類,因此可以注入配置。這裏是我的嘗試:
/*
Dummy controller that has environment and configuration manually injected.
*/
class ConfigurationController(env: play.api.Environment,
conf: play.api.Configuration) extends Controller {
}
/*
Dummy controller that has environment and configuration manually injected, but
sets up a remote client.
*/
class RemoteActorController(env: play.api.Environment, conf: play.api.Configuration)
extends ConfigurationController(env, conf) {
protected val remoteActorName = "foo"
private val remoteActorConf = conf.underlying.getConfig(remoteActorName)
private val system = ActorSystem("HttpServerSystem", ConfigFactory.load())
private val tcpInfo = remoteActorConf.getConfig("akka.remote.netty.tcp")
private val hostname = tcpInfo.getString("hostname")
private val port = tcpInfo.getString("port")
val path = s"akka.tcp://[email protected]$hostname:$port/system/receptionist"
private val initialContacts = Set(ActorPath.fromString(path))
protected val client = system.actorOf(
ClusterClient.props(ClusterClientSettings(system).withInitialContacts(
initialContacts)),
"ClusterClient"
)
}
/*
Actual controller whose actions correspond to endpoints in `conf/routes`.
*/
@Singleton
class BarController @Inject()(env: play.api.Environment,
conf: play.api.Configuration) extends
RemoteActorController(env, conf) {
// ...
}
然而,當我開始我的申請,我覺得演員系統始終未能找到它的端口(即使沒有什麼是偵聽該端口),不考慮的端口號。
play.api.UnexpectedException: Unexpected exception[ProvisionException: Unable to provision, see the following errors:
1) Error injecting constructor, org.jboss.netty.channel.ChannelException: Failed to bind to: /127.0.0.1:8888
似乎是與注射的時機的問題,但我很新的給我在遇到麻煩調試它DI。
我試着在我的build.sbt
中加入routesGenerator := InjectedRoutesGenerator
,並在@
前加上了我的注入路由的相關控制器,但仍然發現相同的運行時異常。
有沒有人有建議?
「無法綁定」通常意味着您已經擁有使用此端口的應用程序,請嘗試將您的配置更改爲使用其他端口。 – vdebergue
@vdebergue這些端口沒有被TCP或UDP使用。 – erip