是否可以使用scala-guice注入对象? [英] Is it possible to inject an object with scala-guice?

查看:100
本文介绍了是否可以使用scala-guice注入对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想注入 scala.io.Source ,但是我找不到有效的解决方案。到目前为止,这是我所拥有的:

I would like to inject the scala.io.Source but I failed to find a working solution. This is what I have so far:

class Foo @Inject()(var source:Source) {
  // ...
}

和绑定:

class DependencyInjection extends AbstractModule with ScalaModule {
  def configure:Unit = {
     bind[Source.type].to[Source]
     // bind[Source] didn't work
  }
}

也许我可以将 scala.io.Source 调用包装到本地 class 中,但这听起来不正确。有没有办法使用scala-guice注入对象?

Maybe I can wrap the scala.io.Source calls into a local class but it doesn't sound right. Is there a way to inject objects with scala-guice?

推荐答案

因为 Source 是一个抽象类,并且没有针对它的公共扩展(即使有公共扩展,您也将无法使用它们,因为它们可能没有启用Guice),您必须使用提供程序或 @Provide 方法。

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.

提供程序:

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]
  }
}

另一种方法是使用 @Provides 方法:

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.

当您需要注入未启用Guice或只能通过工厂方法获得。

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.

这篇关于是否可以使用scala-guice注入对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆