【问题标题】:IntelliJ can't find Spring bean from Kotlin objectIntelliJ 无法从 Kotlin 对象中找到 Spring bean
【发布时间】:2019-04-27 22:58:58
【问题描述】:

我有一个使用 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 的类型。

如果我在“MyObject”中将“object”更改为“class”,错误就会消失。

我的问题是:

  • 是 IntelliJ 的问题吗?
  • 不建议使用@Component注释 Kotlin 对象吗?

【问题讨论】:

    标签: spring intellij-idea kotlin


    【解决方案1】:

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

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

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

    【讨论】:

    • 仍然没有找到解决方案?
    【解决方案2】:

    我建议不要使用带有@Component 或任何其他bean 注释的kotlin 对象。

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

    1. 您的应用程序中可能有多个 ApplicationContext 实例。
    2. Kotlin 对象与特定的ClassLoader 相关

    【讨论】:

      【解决方案3】:

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

      但实际上,如果您知道自己在做什么,并且意识到如果您的 object 变为有状态,则可能会出现“不推荐”的任何原因。

      所以我认为IDEA应该支持你的案子,我已经填了一张票IDEA-211826

      【讨论】:

      • 谢谢@Николай!我会按照你填的票。
      猜你喜欢
      • 2018-10-01
      • 2020-11-24
      • 2020-10-02
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      相关资源
      最近更新 更多