You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Cloud Stream中Source类引用失败问题求助

解决方案:Spring Cloud Stream 4.x 中无法找到Source类的问题

问题根源

Spring Cloud Stream 4.0+ 版本已移除了org.springframework.cloud.stream.messaging.Source类,这是官方的API重大变更,并非依赖缺失或Kotlin兼容问题。

具体解决步骤

1. 规范依赖版本管理

使用Spring Cloud BOM统一管理版本,避免版本冲突。在pom.xml中添加:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2022.0.4</version> <!-- 对应Spring Cloud Stream 4.0.4 -->
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

同时确保spring-cloud-stream-binder-kafka依赖无需手动指定版本,会自动匹配BOM中的版本。

2. 替换Source的两种方案

方案一:使用函数式编程模型(官方推荐)

Spring Cloud Stream 3.x起推荐使用函数式模型替代传统的@EnableBinding方式,示例Kotlin代码:

import org.springframework.context.annotation.Bean
import org.springframework.messaging.Message
import org.springframework.messaging.support.MessageBuilder
import java.util.function.Supplier

@Bean
fun messageSender(): Supplier<Message<String>> {
    return Supplier {
        MessageBuilder.withPayload("your message content").build()
    }
}

在application.yml中配置绑定关系:

spring:
  cloud:
    function:
      definition: messageSender # 对应上面Bean的方法名
    stream:
      bindings:
        messageSender-out-0:
          destination: your-target-topic # 消息发送的目标主题/通道
方案二:自定义输出通道(兼容旧代码风格,不推荐长期使用)

如果需要临时兼容旧代码结构,可以自定义类似Source的接口,注意@EnableBinding已被标记为废弃:

import org.springframework.cloud.stream.annotation.Output
import org.springframework.messaging.MessageChannel

interface CustomSource {
    @Output("output")
    fun output(): MessageChannel
}

在启动类添加注解启用绑定:

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.cloud.stream.annotation.EnableBinding

@SpringBootApplication
@EnableBinding(CustomSource::class)
class YourApplication

fun main(args: Array<String>) {
    runApplication<YourApplication>(*args)
}

之后可以通过注入CustomSource来发送消息:

import org.springframework.stereotype.Component
import org.springframework.messaging.support.MessageBuilder

@Component
class MessageProducer(private val customSource: CustomSource) {
    fun sendMessage(content: String) {
        customSource.output().send(MessageBuilder.withPayload(content).build())
    }
}

3. 工程缓存与依赖校验

  • 执行mvn dependency:tree命令,检查spring-cloud-stream依赖是否被正确引入,无排除或冲突情况。
  • 在IntelliJ中执行File -> Invalidate Caches... -> Invalidate and Restart,清除IDE缓存后重新加载项目。
  • 若本地maven仓库存在损坏的jar包,删除~/.m2/repository/org/springframework/cloud/spring-cloud-stream/4.0.4目录,重新执行mvn clean install -U下载完整依赖。

内容的提问来源于stack exchange,提问作者Rysic Rychu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 19:32:28