从配置kafkalistener中读取

问题描述 投票:0回答:2

我有一个 Spring Boot 应用程序,其侦听器如下:

@KafkaListener(id = "demo", topics = "demo",
            containerFactory = "retryKafkaListenerContainerFactory")
    public void receive(ConsumerRecord<String, String> consumerRecord, Acknowledgment acknowledgment) throws Exception {

}

我有 apache 配置对象,我想用它来从属性中读取主题。我知道我可以使用属性占位符来做到这一点。但我使用的配置内部有一些逻辑,因此只想从该配置对象中读取。如下:

@Inject
private Configuration configuration

我可以获取主题为

configuration.getString("kafka.consumer.topic")
。我尝试像这样使用:
topics = "#{configuration.getString('kafka-generic.consumer.topics')}"
在 KafkaListener 注释的主题字段中,但出现以下错误。

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'configuration' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:224)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:81)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:51)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:87)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:242)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:161)
    ... 23 common frames omitted

有人可以告诉我如何在KafkaListener注释的topics字段中使用

configuration.getString("kafka.consumer.topic")
吗?

java spring apache-kafka kafka-consumer-api spring-kafka
2个回答
1
投票

出现错误。

对于这样的问题来说,这还远远不够;你必须显示实际的错误。

您可以使用 SpEL

topics = "#{@somebean.someProperty}" or
主题 =
"#{@somebean.getString('...')}"


0
投票

如果可能,您可以使用

等属性中的一个

application.properties

app.kafka.topic=myTopic

@KafkaListener(topics = "${app.kafka.topic}")

© www.soinside.com 2019 - 2024. All rights reserved.