Jacket
Jacket

Reputation: 393

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

Upvotes: 4

Views: 10052

Answers (2)

shasr
shasr

Reputation: 375

You can use below entry in application.yml file

enter image description here

Usually we use @Value as below to pick data from properties/yaml files for a specified key in you Java class as below.

@Value("${kafka.topic.name}")
private String TOPIC_NAME;

Since Kafka Listener expects constant here, you can use directly as below

public class KafkaConsumer {

@Autowired
private UserRepository userRepository;


@KafkaListener(topics = "${kafka.topic.name}")
public void listen(@Validate UserDto userDto) {

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

}

Upvotes: 4

Numero 21
Numero 21

Reputation: 265

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.

Upvotes: 8

Related Questions