@PostConstruct 并自动装配一个 MessageChannel

@PostConstruct and autowiring a MessageChannel

我在使用 Spring Cloud Stream 时遇到问题。问题是我有一个 bean,它会在创建后立即写入 Kafka(用 @PostConstruct 注释的方法),所以我自动装配适当的 MessageChannel 并在 application.yml 中设置目标和活页夹属性。它是这样的:

@Component
@RequiredArgsConstructor
public class Sender
{
    private final MessageChannel output;

    @PostConstruct
    public void start()
    {
       output.send(new GenericMessage("Hello world");  
    }
}

和application.yml

spring:
    cloud:
        stream:
            bindings:
              output:
                destination: someData
                binder: kafka

我还有以下依赖:

- spring-cloud-stream-reactive
- reactor-core
- spring-cloud-starter-stream-kafka

项目本身正在启动,但在尝试写入 start() 方法中的 output 时出现以下异常:

Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers

是因为kafka binder还没成功绑定channel还是什么?如果是这样,替代方法是什么。

提前致谢。

您不能在 @PostConstruct 中执行此操作。太早了。其他组件可能尚未初始化。

您必须将发送逻辑移至 SmartLifecycle.start() 实现。