Search code examples
springapache-kafkaspring-kafka

Spring-Kafka: How to pass the kafka topic from the application.yml


I have a small project in Spring Kafka I wish I could pass my kafka topic from application.yml and avoid a hard-coding problem. For the moment I have this situation:


public class KafkaConsumer {
    @Autowired
    private UserRepository userRepository;


    @KafkaListener(topics = "myTopic")
    public void listen(@Validate UserDto userDto) {

        User user= new User(userDto);
        userRepository.save(userDto.getAge(), user);
    }
}

at this moment I have the static kafka topic (being a string) is it possible to put it in the application.yml and have it read from there? Thanks everyone for any help


Solution

  • You can post your topic in the application.yml :

    kafka:
      template:
        default-topic: "MyTopic"
    

    In your KafkaListerner :

    @KafkaListener(topics = "#{'${spring.kafka.template.default-topic}'}")
    

    So you should solve the problem of the "Attribute Value" failing to take a dynamic value

    This worked for me.