我有playframework项目,并且向其中添加了Firebase库。使用前需要初始化Firebase。所以我创建了这段代码:
class Module extends AbstractModule with ScalaModule {
override def configure(): Unit = {
bind[Init].asEagerSingleton()
}
}
class Init @Inject()(
//some deps here
)(implicit val ec: ExecutionContext) {
val options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.build()
FirebaseApp.initializeApp(options)
}
在run
之后,它第一次可以正常运行,但是在自动重新加载(一些代码更改)之后,出现了这个错误:
java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
at global.Init.<init>(Init.scala:17)
因为sbt试图初始化Firebase,但它已经初始化。
我这样解决:
class Init @Inject()(
//some deps here
)(implicit val ec: ExecutionContext) {
try {
FirebaseApp.getInstance()
} catch {
case e: IllegalStateException =>
val options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.build()
FirebaseApp.initializeApp(options)
}
}
但是也许有人有更好的解决方案?