Is it possible to inject an object with scala-guice?

倾然丶 夕夏残阳落幕 提交于 2019-12-07 08:14:26

Because Source is an abstract class, and there are no public extensions for it (and even if there were, you wouldn't be able to use them anyway since they likely wouldn't have been Guice-enabled), you'll have to use providers or @Provide methods.

Providers:

class Config extends AbstractModule with ScalaModule {
  override def configure: Unit = {
    bind[Source].toProvider(new Provider[Source] {
      override def get = Source.fromFile("whatever.txt")(Codec.UTF8)
    })
  }
}

// you can also extract provider class and use `toProviderType[]` extension 
// from scala-guice:

class FromFileSourceProvider extends Provider[Source]
  override def get = Source.fromFile("whatever.txt")(Codec.UTF8)
}

class Config extends AbstractModule with ScalaModule {
  override def configure: Unit = {
    bind[Source].toProviderType[FromFileSourceProvider]
  }
}

Another way is to use @Provides methods:

class Config extends AbstractModule with ScalaModule {
  @Provides def customSource: Source = Source.fromFile("whatever.txt")(Codec.UTF8)
  // that's it, nothing more
}

I'd also suggest adding a binding annotation to distinguish between different sources in your program, though it entirely depends on your architecture.

This approach is no different from that in Java, when you need to inject classes which are not Guice-enabled or available through factory methods only.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!