我想使用DI谷歌guice在Java中工作得非常好,但在scala的情况下不工作,或者我错过了什么... 谁能指出来。
模块。
class ConfigModule extends AbstractModule{
override def configure(): Unit = {
}
@Provides
@Named("config")
def getConfig(): Config = {
new Config
}
}
配置
class Config {
val config1: String = "Sample"
}
服务项目
class Service(@Named("config") config:Config) {
def read(): Unit = {
println("Reading")
}
}
主课
object SampleJob {
def main(args: Array[String]): Unit = {
val injector = Guice.createInjector(new ConfigModule)
val service = injector.getInstance(classOf[Service])
service.read()
}
}
错误。
1) Could not find a suitable constructor in com.job.Service. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
at com.job.Service.class(Service.scala:7)
while locating com.job.Service
如果有任何帮助,我将非常感激
先谢谢你
UPDATE。
class Service(@Inject @Named("config") config:Config) {
def read(): Unit = {
println("Reading")
}
}
这也给出了同样的错误
在 com.job.Service.class(Service.scala:8) 找不到合适的构造函数。类必须有一个(且只有一个)注解为@Inject的构造函数,或者是一个非私有的零参数构造函数。在com.job.Service.class(Service.scala:8),当定位com.job.Service
这个错误告诉你发生了什么。
Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private
所以你需要添加 @Inject
注释 你的构造者 喜欢 在教程中.
而不是
class Service(@Inject @Named("config") config:Config) {
def read(): Unit = {
println("Reading")
}
}
应该是
class Service @Inject() (@Named("config") config:Config) {
def read(): Unit = {
println("Reading")
}
}