如何在Spring中将依赖类中的bean定义为@Primary



我有一个Kafka Consumer,我正在使用Spring Cloud Stream Source.class绑定和InboundChannelAdapter实现它。这个Source.class定义了3个MessageChannel bean:output、nullChannel和errorChannel。我的代码如下:

@EnableBinding(Source.class)
@Import(KafkaSourceConfig.class)
public class KafkaSource {
@Autowired
MessageChannel controlBusChannel;
@InboundChannelAdapter(value = Source.OUTPUT, poller = @Poller(fixedDelay = "1"), autoStartup = "false")
public AgentActivityNoteCreated consumeAndSendMessage() {
// UNIMPORTANT CODE
}
}

我想在输出通道中自动连线,这样我就可以使用它手动启动和停止InboundChannelAdapter,但在尝试自动连线时遇到了这个错误。

Field controlBusChannel in com.company.KafkaSource required a single bean, but 3 were found:
- output: defined by method 'output' in null
- nullChannel: defined in null
- errorChannel: defined in null
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

我理解这个错误,应用程序不知道要注入3个bean中的哪一个,但不知道如何将输出通道标记为Primary,因为我实际上并没有制作bean。我该怎么做?

如果代码中没有Bean定义。然后,以下应该起作用:

@Autowired
@Qualifier("output")
MessageChannel controlBusChannel;

参考:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-自动连线注释限定符

最新更新