Search code examples
javaspring-kafkaspring-boot-actuatorspring-boot-test

How to get spring boot default Kafka consumer object


My configurations for Kafka consumer are in the application.yaml file. I know that if I only have 1 consumer, I don't need to create a consumerFactory bean and it would be set by spring by default. I need to test my consumer so I need to access the consumer object in my test file and I don't want to config it again (I want to use the default configuration in the application.yaml) file to create a consumer object. How is this possible?


Solution

  • Spring Boot provides a comprehensive enough auto-configuration for Spring Kafka: https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/spring-boot-features.html#boot-features-kafka.

    There is this set of beans you can inject into your test class:

    • KafkaTemplate<?, ?> kafkaTemplate
    • ProducerListener<Object, Object> kafkaProducerListener
    • ConsumerFactory<?, ?> kafkaConsumerFactory
    • ProducerFactory<?, ?> kafkaProducerFactory
    • KafkaTransactionManager<?, ?> kafkaTransactionManager
    • KafkaJaasLoginModuleInitializer kafkaJaasInitializer
    • KafkaAdmin kafkaAdmin
    • ConcurrentKafkaListenerContainerFactoryConfigurer kafkaListenerContainerFactoryConfigurer
    • ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory
    • KafkaStreamsConfiguration defaultKafkaStreamsConfig
    • KafkaStreamsFactoryBeanConfigurer kafkaStreamsFactoryBeanConfigurer

    So, to get a KafkaConsumer in your test, you need to autowire a ConsumerFactory and call its createConsumer() and you'll get a fresh instance based on the configuration properties.