IntelliJ无法从Kotlin对象中找到Spring bean

问题描述 投票:0回答:3

我有一个用IntelliJ 2019.1打开的Spring Boot 2 + Kotlin应用程序。

在这个应用程序中,我用@Component注释了一些Kotlin对象。例:

@Component
object MyObject: MyInterface {
    // code
}

我有许多不同的MyInterface实现(都使用Kotlin对象),我想将它们全部注入另一个bean的列表中。例:

@Component
class MyComponent @Autowired constructor(private val objects: List<MyInterface>) {
    // code
}

代码运行正常(bean在列表objects中注入)但IntelliJ显示错误说:

无法自动装配。没有豆'?扩展MyInterface'或'List <?扩展了MyInterface>'找到的类型。

如果我在'MyObject'中将'object'更改为'class',则错误消失。

我的问题是:

  • 这是IntelliJ的问题吗?
  • 是不是不建议用@Component注释Kotlin对象?
spring intellij-idea kotlin
3个回答
1
投票

使用Kotlin对象作为@Component-s有点奇怪,因为如果你的类知道它将在Spring容器中使用,你将获得更大的灵活性,如果你委托给Spring,那么这个类是否应该是单例的决定以及所有其他生命周期管理。

但实际上,如果你知道自己在做什么,并且知道如果你的object成为有状态可能会发现错误,我认为没有任何理由可以“不推荐”。

所以我认为IDEA应该支持你的情况,而且我已经填了一张IDEA-211826


1
投票

有关信息,作为一种可能的解决方法,虽然Николай在ticket创建的this answer未被处理,但我忽略了错误/警告,只有我需要@Suppress("SpringJavaInjectionPointsAutowiringInspection")。例:

@Suppress("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private lateinit var kotlinObjectBeans: List<MyInterface>

我希望它可以帮助那些不想在其他地方禁用此检查的人。


0
投票

我建议不要将kotlin对象与@Component或任何其他bean注释一起使用。

有两个方面,混合它们会导致很多问题:

  1. 它可能是您的应用程序中的几个ApplicationContext实例。
  2. Kotlin对象与特定的ClassLoader有关
© www.soinside.com 2019 - 2024. All rights reserved.