chris01
chris01

Reputation: 12431

Spring Boot: How to concat annotations

I have a annotation in Spring-Boot.

@KafkaListener (topicPattern = "mytopic1")

I have also a variable in my application.properties.

myvar = abc

Not I like to add myvar to my topicPattern. Is that possible??

So the resulting string used at runtime should by

@KafkaListener (topicPattern = "mytopic1abc")

Is that possible??

It should only work, if myvar is not set - thats also possible?

Upvotes: 1

Views: 98

Answers (1)

Matheus Barros
Matheus Barros

Reputation: 11

In Spring Boot, you can use the @Value annotation along with SpEL (Spring Expression Language) to dynamically construct the topicPattern attribute of @KafkaListener at runtime based on the value of the myvar property in your application.properties file.

Here's an example of how you can achieve this:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

@Service
public class KafkaListenerService {

    @Value("${myvar:}")
    private String myvar;

    @KafkaListener(topicPattern = "mytopic1${myvar}")
    public void listen(String message) {
        // Your Kafka listener logic here
        System.out.println("Received message: " + message);
    }
}

Upvotes: 1

Related Questions