Kotlin Spring: Unresolved reference method



我在文件A中有以下类:

@Service
class MyService(
private val myLoader: Loader
) {
fun load(myKey: SomeKey) =
myLoader.loadStuff(myKey)
}

我想在另一个文件B中像这样调用这个函数:

MyService.load(myKey)

但是,load()方法在IntelliJ中被标记为红色。错误提示"未解析的引用:load";我不知道为什么当我输入MyService.时,IntelliJ甚至建议加载方法。

如何解决这个问题?

由于您正在使用Spring,应该调用MyService的其他组件也必须是Spring管理的Bean,以便它可以获得MyServiceBean的控制。文件B中的组件应该如下所示:

@Service
class MyServiceB (
private val myService: MyService
) {
fun test(myKey: SomeKey) = myService.load(myKey)
}

注意@Service注释使其成为Spring管理的Bean,并且MyServiceMyServiceB构造函数的参数,这告诉Spring必须注入MyService类型的Bean。


如果你有一个对象而不是一个类,你将不得不做如下的事情:

object MyServiceB (
lateinit var myService: MyService
) {
fun test(myKey: SomeKey) = myService.load(myKey)
}
@Configuration
class MyServiceBConfiguration(private val myService: MyService) {
@Bean
fun myServiceB(): MyServiceB {
return MyServiceB.also {
it.myService = myService
}
}
}

这应该可以工作,但我绝对不建议这样做。这是一个hack,绝对不是一个干净的解决方案。考虑一下我最初的建议。

相关内容

最新更新