1

在创建 Play 框架项目并使用WSClientREST 调用时,官方 Play 框架文档建议添加wsbuild.sbt管理依赖项。如果使用 Maven,则 ws 依赖项包含在:

<dependency>
  <groupId>com.typesafe.play</groupId>
  <artifactId>play-ws_2.12</artifactId>
  <version>${play2.version}</version>
</dependency>

但是,当尝试使用这样的片段调用 Web 服务时:

@Singleton
class Controller @Inject()(
  ws: WSClient,
  controllerComponents: ControllerComponents
)(implicit ec: ExecutionContext)
  extends AbstractController(controllerComponents) {
  def callApi(): Action[AnyContent] = Action.async { _ =>
    ws
      .url("https://mywebservice.com/api/bla")
      .get()
      .map(response => Ok(response.body.toString))
  }
}

然后出现以下错误:

CreationException: Unable to create injector, see the following errors:

1) No implementation for play.api.libs.ws.WSClient was bound.
  while locating play.api.libs.ws.WSClient
    for the 1st parameter of controllers.MyController.<init>(MyController.scala:13)
  while locating controllers.MyController
    for the 3rd parameter of router.Routes.<init>(Routes.scala:33)
  at play.api.inject.RoutesProvider$.bindingsFromConfiguration(BuiltinModule.scala:123):
Binding(class router.Routes to self) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$4)
4

1 回答 1

4

正如文档所说:

注意:在 Play 2.6 中,Play WS 被分为两部分,一个不依赖于 Play 的底层独立客户端,以及一个使用 Play 特定类的包装器。此外,AsyncHttpClient 和 Netty 的阴影版本现在在 Play WS 中使用以最大程度地减少库冲突,主要是为了让 Play 的 HTTP 引擎可以使用不同版本的 Netty。有关详细信息,请参阅 2.6 迁移指南。

查看 2.6 迁移指南,我们可以阅读:

如果您有一个 Play SBT 项目,您仍然可以通过将以下行添加到您的 build.sbt 来添加 WS:

libraryDependencies += ws

这包括 play-ahc-ws 模块 [...]

所以要解决这个问题,我们必须将play-ahc-ws模块添加到 Maven 的 pom.xml 中:

<dependency>
  <groupId>com.typesafe.play</groupId>
  <artifactId>play-ahc-ws_2.12</artifactId>
  <version>${play2.version}</version>
</dependency>

如果在代码示例中使用 Guice,则依赖注入将由 Guice 处理。

于 2019-02-25T12:45:39.860 回答