clusterSettings不是com.mongodb.MongoClientSettings.Builder的成员

时间:2018-06-06 11:52:25

标签: mongodb scala sbt

我正在尝试使用scala中的mongodb客户端。我使用IntelliJ IDEA。

在这一行:

val settings: MongoClientSettings = MongoClientSettings
                                             .builder()
                                             .clusterSettings(clusterSettings)
                                             .build()

我收到错误:

  

clusterSettings不是com.mongodb.MongoClientSettings.Builder的成员

尽管依赖关系和导入似乎是正确的。

这是sbt文件:

scalaVersion := "2.11.12"
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "2.3.0"
libraryDependencies += "org.mongodb" % "mongodb-driver-core" % "3.7.0"

这里包括:

import com.mongodb.ServerAddress
import org.mongodb.scala.MongoClientSettings
import org.mongodb.scala.connection.ClusterSettings

似乎没有人在互联网上出现这个问题,但我的同事最近也有同样的问题。任何想法在这里有什么问题?

更新

根据罗斯的评论我修改了sbt:

scalaVersion := "2.11.12"
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "2.3.0"

修改后的代码:

import com.mongodb.connection.ClusterSettings
import org.mongodb.scala.MongoClientSettings

val settings: MongoClientSettings = MongoClientSettings
  .builder()
  .applyToClusterSettings((b: ClusterSettings.Builder) => b.applySettings(clusterSettings))
  .build()

现在IDEA没有抱怨并且它看到所有API,但在编译期间我收到错误:

  

错误:(9,60)类型不匹配;    发现:com.mongodb.connection.ClusterSettings.Builder => com.mongodb.connection.ClusterSettings.Builder    必需:com.mongodb.Block [com.mongodb.connection.ClusterSettings.Builder]         .applyToClusterSettings((b:ClusterSettings.Builder)=> b.applySettings(clusterSettings))

但是如果我在外面定义块然后使用它 - 它会成功编译:

 val block: Block[ClusterSettings.Builder] = new Block[ClusterSettings.Builder] {
  override def apply(t: ClusterSettings.Builder): Unit = {
    t.applySettings(clusterSettings)
  }
}

val settings: MongoClientSettings = MongoClientSettings
  .builder()
  .applyToClusterSettings(block)
  .build()

可能是什么原因?

1 个答案:

答案 0 :(得分:6)

2.3.0中MongoClientSettings的类型别名发生了变化,其API与上一个构建器略有不同。请参阅升级指南:http://mongodb.github.io/mongo-scala-driver/2.3/upgrade/#mongoclientsettings

更改原因是因为com.mongodb.async.client.MongoClientSettings已被弃用,而支持新的集中式MongoClientSettings

您现在仍可以使用已弃用的设置。更新(刷新)你的sbt项目,intellij将突出显示构建器上缺少clusterSettings方法。

将设置应用于新MongoClientSettings

的示例
import com.mongodb.connection.ClusterSettings

// Scala 2.12 (support for Single Abstract Methods)
val clientSettings: MongoClientSettings = MongoClientSettings
      .builder()
      .applyToClusterSettings((b: ClusterSettings.Builder) => b.applySettings(clusterSettings))
      .build()

// Scala 2.11 you must provide the block:
val clientSettings: MongoClientSettings = MongoClientSettings
      .builder()
      .applyToClusterSettings(new Block[ClusterSettings.Builder]() {
        override def apply(b: ClusterSettings.Builder): Unit = b.applySettings(clusterSettings)
      })
      .build()