This week, I learned that when we use Kafka, the @EnableKafka
annotation is not needed if an application is a Spring Boot application. We only need it if we are developing with Spring, not Spring Boot.
This is because Spring Boot includes KafkaAnnotationDrivenConfiguration
, which is enabled when there is the @EnableKafka
annotation class on the classpath. KafkaAnnotationDrivenConfiguration
adds @Configuration
with @EnableKafka
, so that we don't need to add it again to one of our configurations:
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(EnableKafka.class)
class KafkaAnnotationDrivenConfiguration {
// ...
@Configuration(proxyBeanMethods = false)
@EnableKafka
@ConditionalOnMissingBean(name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
static class EnableKafkaConfiguration {
}
}
And the @EnableKafka
annotation class is present on the classpath when we add org.springframework.kafka:spring-kafka
as a dependency.
Duplicating @EnableKafka
does not hurt, however,
- Why add it again if it is already there?
- More importantly, we need to understand the effect of the annotations we use. If we don't, we may end up with an application that fails to start (in the best case) or has weird issues that are hard to reproduce and debug (in the worst case).
The confusion about whether the @EnableKafka
annotation is required or not may come from the following:
- Many sources on the Internet use
@EnableKafka
annotation with Spring Boot. Here is an example: Intro to Apache Kafka with Spring. - The Javadoc for
@EnableKafka
does not say anything about Spring Boot. It only states that we need to use this annotation on@Configuration
classes. This is probably fair, sincespring-kafka
(which contains@EnableKafka
) does not know anything about Spring Boot or auto-configurations. However, this is still misleading.
In conclusion, the next time you use Kafka with Spring Boot, you know the drill - do not duplicate @EnableKafka
on your configurations.
Dream your code, code your dream.