@PostConstruct 并自动装配 MessageChannel [英] @PostConstruct and autowiring a MessageChannel
问题描述
我在使用 Spring Cloud Stream 时遇到问题.问题是我有一个 bean,它会在创建后立即写入 Kafka(使用 @PostConstruct 注释的方法),因此我自动装配了适当的 MessageChannel 并在 application.yml 中设置了目标和绑定器属性.它是这样的:
I'm having a problem with Spring Cloud Stream. The thing is that I have a bean that will write to Kafka as soon as it's created (method annotated with @PostConstruct), so I autowire the appropriate MessageChannel and set the destination and binder properties in application.yml. It goes like this:
@Component
@RequiredArgsConstructor
public class Sender
{
private final MessageChannel output;
@PostConstruct
public void start()
{
output.send(new GenericMessage("Hello world");
}
}
和 application.yml
And application.yml
spring:
cloud:
stream:
bindings:
output:
destination: someData
binder: kafka
我还有以下依赖项:
- spring-cloud-stream-reactive
- reactor-core
- spring-cloud-starter-stream-kafka
项目本身正在启动,但在尝试写入 start()
方法中的 output
时出现以下异常:
The project itself is starting, but I'm getting the following exception when trying to write to the output
in start()
method:
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
是因为 Kafka binder 还没有设法绑定 channel 还是什么?如果是这样,有什么替代方法.
Is it because Kafka binder didn't manage to bind the channel yet or what? If so, what is the alternative way to this.
提前致谢.
推荐答案
您不能从 @PostConstruct
中做到这一点.太早了.其他组件可能尚未初始化.
You can't do that from the @PostConstruct
. It's too early. Other components might be initialized yet.
您必须将发送逻辑移至 SmartLifecycle.start()
实现.
You have to move your sending logic to the SmartLifecycle.start()
implementation.
这篇关于@PostConstruct 并自动装配 MessageChannel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!