Spring Boot: How to concat annotations

56 Views Asked by At

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?

1

There are 1 best solutions below

1
Matheus Barros On

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);
    }
}