-2

why for a later method I do not need to require @Autowired to inject consumerFactory? And when I do so I receive a circular dependency exception. Am I missing something fundamental, I guess yes. Thanks for the help.

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfig());
    }

    @Bean
    public KafkaListenerContainerFactory<
            ConcurrentMessageListenerContainer<String, String>> factory(
            ConsumerFactory<String, String> consumerFactory
    ) {

        ConcurrentKafkaListenerContainerFactory<String, String> factory =
                new ConcurrentKafkaListenerContainerFactory<>();

        factory.setConsumerFactory(consumerFactory);
        return factory;
    }
naruto
  • 69
  • 5

2 Answers2

1

Spring automatically detects that the @Bean annotated method factory() requires a ConsumerFactory to create an instance of KafkaListenerContainerFactory. Hence it already knows that it needs to provide a dependency for that.

@Autowired is only required if you have a class that requires a dependency, for example:

@Component
public class SomeClass {

   @Autowired
   private ConsumerFactory<String, String> consumerFactory;

}

An alternative to this would be to define this as constructor argument, then you don't need @Autowired as well as it's already clear thanks to the constructor signature:

@Component
public class SomeClass {

   private ConsumerFactory<String, String> consumerFactory;

   public SomeClass(ConsumerFactory<String, String> consumerFactory) {
      this.consumerFactory = consumerFactory;
   }

}
Markus
  • 1,649
  • 1
  • 22
  • 41
1

You use a method defined in the same class to initialize the ConsumerFactory object (I suspect it's a configuration class annotated with @Configuration).

The @Bean annotation creates another element and adds it to the set maintained by Spring engine.

Oskarro
  • 323
  • 2
  • 9