问题
I AM WRITING A KAFKA CONSUMER I want to pass the environment variable topic name to @kafkalistener(topics = topic
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaConsumer {
@Autowired
private EnvProperties envProperties;
private final String topic = envProperties.getTopic();
@KafkaListener(topics = "#{'${envProperties.getTopic()}'}",
groupId = "group_id")
public void consume(String message){
logger.info("Consuming messages " +envProperties.getTopic());
}
}
topics = "#{'${envProperties.getTopic()}'}" AT THIS LINE IT IS THROWING ERROR . MY APPLICATION FAILS TO START. hOW TO SET THIS TOPIC NAME DYNAMICALLY FROM ENVIRONMENT VARIABLE.
回答1:
Normally, you can't reference fields or properties from the bean in which the SpEL is declared. However, @KafkaListener
has special syntax to support it.
See the documentation.
Starting with version 2.1.2, the SpEL expressions support a special token
__listener
which is a pseudo bean name which represents the current bean instance within which this annotation exists.
So, if you add public EnvProperties getEnvProperties()
to the class then something like
#{__listener.envProperties.topic}
should work.
来源:https://stackoverflow.com/questions/54038928/how-to-pass-dynamic-topic-name-to-kafkalistenertopics-from-environment-variabl