是否可以使用scala guice注入对象?
我想注入是否可以使用scala guice注入对象?,scala,dependency-injection,guice,Scala,Dependency Injection,Guice,我想注入scala.io.Source,但找不到有效的解决方案。这就是我到目前为止所做的: class Foo @Inject()(var source:Source) { // ... } 以及约束力: class DependencyInjection extends AbstractModule with ScalaModule { def configure:Unit = { bind[Source.type].to[Source] // bind[Sour
scala.io.Source
,但找不到有效的解决方案。这就是我到目前为止所做的:
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
调用封装到本地类中,但听起来不太对劲。有没有办法用scala guice注入对象?因为源代码
是一个抽象类,并且没有公共扩展(即使有,您也无法使用它们,因为它们可能没有启用guice),所以您必须使用提供程序或@Provide
方法
供应商:
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]
}
}
另一种方法是使用@提供方法:
class Config extends AbstractModule with ScalaModule {
@Provides def customSource: Source = Source.fromFile("whatever.txt")(Codec.UTF8)
// that's it, nothing more
}
我还建议添加一个绑定注释来区分程序中的不同源,尽管这完全取决于您的体系结构
这种方法与Java中的方法没有什么不同,当您需要注入未启用GUI或仅通过工厂方法可用的类时。我从未使用过ScalaModule
,但是不管怎样,你怎么能将源代码
与自身绑定呢?根据定义源代码。type
只由源代码
占据。这使得它的注入毫无意义-唯一可以注入的东西可以是源代码
本身,你也可以直接使用它。顺便说一句,请澄清:你想注入源代码
伴生对象(类型源代码.type
)还是想注入源代码
类的某个实例(类型源代码
)?这些都是非常不同的事情,注入源伴生对象是毫无意义的,正如我所说的那样。@Jatin我尝试了一切-没有绑定,绑定到自身,绑定到.type,但什么都不起作用。@VladimirMatveev the Source.type只是一个尝试,因为其他任何东西都不起作用,我在其他问题中看到这可能起作用。我认为注入是有效的这不是毫无意义的,因为在我的类中,我希望控制源代码,这样在测试期间它就不会在文件系统上做任何事情。