Skip to content

Instantly share code, notes, and snippets.

@pavelfomin
Last active July 25, 2025 16:19
Show Gist options
  • Save pavelfomin/392700f4fba4ca434c3e51887b7be304 to your computer and use it in GitHub Desktop.
Save pavelfomin/392700f4fba4ca434c3e51887b7be304 to your computer and use it in GitHub Desktop.
Create Kafka topic in a Spring Boot application
@Configuration
public class KafkaConfig {
@Bean
public NewTopic fooTopic(@Value("${app.topics.fooTopic}") String topic) {
return TopicBuilder.name(topic)
.partitions(8)
.build();
}
@Bean
public Collection<NewTopic> barTopics(@Value("${app.topics.barTopic}") String topic) {
return List.of(
TopicBuilder.name(topic)
.partitions(4)
.build(),
TopicBuilder.name(topic + "-dlt")
.partitions(4)
.build(),
TopicBuilder.name(topic + "-retry")
.partitions(4)
.build()
);
}
}

If the producers rely on the topic auto creation to create topics upon first message produced, sometimes producers might want to create topics ahead of time so consumers can be deployed before the first message is produced. One way to accomplish this is to expose NewTopic instance as a @Bean and deploy this change in all environments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment