我正在编写一个 Kafka 消费者。我需要将环境变量主题名称传递给 @KafkaListener(topics = ...)
。这是我到目前为止所尝试过的:
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()}'}"
行收到错误,应用程序无法启动。
如何从环境变量动态设置此主题名称?
最佳答案
通常,您不能引用声明 SpEL 的 bean 中的字段或属性。但是,@KafkaListener 有特殊的语法来支持它。
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.
因此,如果您将 public EnvProperties getEnvProperties()
添加到类中,则类似
#{__listener.envProperties.topic}
应该可以。
关于java - 如何从环境变量将动态主题名称传递给@KafkaListener(topics),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54038928/