Skip to content
Advertisement

How to define a bean from a dependency class as @Primary in Spring?

I have a Kafka Consumer and I’m implementing it using the Spring Cloud Stream Source.class binding and InboundChannelAdapter. This Source.class defines 3 MessageChannel beans: output, nullChannel, and errorChannel. My code looks like this:

@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
    }
}

I want to autowire in the output channel so that I can use it to start and stop my InboundChannelAdapter manually, but I’m getting this error when trying to autowire.

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

I understand the error, the app doesnt know which of the 3 beans to inject, but don’t know how to mark the output channel as Primary since I didn’t actually make the bean. How do I do that?

Advertisement

Answer

If the Bean definition is not present in your code. Then, following should work:

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

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-autowired-annotation-qualifiers

Advertisement