在注释值中使用 SPEL 时需要帮助吗?
Need help in using SPEL in Annotation Value?
已尝试使用以下 SPEL 表达式,但无法正常工作。需要帮助!
@KafkaListener(topics = "#{Arrays.asList(${kafka.topic.helloworld}.split(',')).stream().map(p -> p+envSuffix).toArray(String[]::new)}")
首先,我看到 ${kafka.topic.helloworld}
必须包装到 ''
,只是因为 property-placeholder 首先工作,然后 SpEL 会将结果视为一个活动变量。例如,你有 foo,bar,baz
。它在 Java 中看起来如何?无非是错误的代码。但是当它是 "foo,bar,baz"
时,语言知道它是一个字符串。与 SpEL 相同 - 它必须像 '${kafka.topic.helloworld}'
.
但这还不是全部。恐怕 SpEL 不支持 lambda。我建议你有一些实用 bean,你可以从这个表达式中调用它,比如:
@KafkaListener(topics = "myUtility.parseTopics('${kafka.topic.helloworld}')")
所有硬转换逻辑都将在 parseTopics()
实用程序 Java 方法中完成。
SpEL 中有一个集合 Projection feature,但您仍然需要在这里和那里进行数组操作。
解决方法是:其中一种在注解中加入lambda的方法如下:
在 KafkaReceiver class 的方法中 -
@Autowired
TopicUtil topicUtil;
@KafkaListener(topics = "#{topicUtil.suffixTopics()}")
//In the TopicUtil - add the follwoing method
public String[] suffixTopics() {
return Arrays.asList(pTopics.split(",")).stream().map(p -> p + envSuffix).toArray(String[]::new);
}
@Tuneit 可以这样直接设置kafka主题吧。
@KafkaListener(topics = "${kafka.topic.helloworld}")
application.properties
kafka.topic.helloworld=
已尝试使用以下 SPEL 表达式,但无法正常工作。需要帮助!
@KafkaListener(topics = "#{Arrays.asList(${kafka.topic.helloworld}.split(',')).stream().map(p -> p+envSuffix).toArray(String[]::new)}")
首先,我看到 ${kafka.topic.helloworld}
必须包装到 ''
,只是因为 property-placeholder 首先工作,然后 SpEL 会将结果视为一个活动变量。例如,你有 foo,bar,baz
。它在 Java 中看起来如何?无非是错误的代码。但是当它是 "foo,bar,baz"
时,语言知道它是一个字符串。与 SpEL 相同 - 它必须像 '${kafka.topic.helloworld}'
.
但这还不是全部。恐怕 SpEL 不支持 lambda。我建议你有一些实用 bean,你可以从这个表达式中调用它,比如:
@KafkaListener(topics = "myUtility.parseTopics('${kafka.topic.helloworld}')")
所有硬转换逻辑都将在 parseTopics()
实用程序 Java 方法中完成。
SpEL 中有一个集合 Projection feature,但您仍然需要在这里和那里进行数组操作。
解决方法是:其中一种在注解中加入lambda的方法如下: 在 KafkaReceiver class 的方法中 -
@Autowired
TopicUtil topicUtil;
@KafkaListener(topics = "#{topicUtil.suffixTopics()}")
//In the TopicUtil - add the follwoing method
public String[] suffixTopics() {
return Arrays.asList(pTopics.split(",")).stream().map(p -> p + envSuffix).toArray(String[]::new);
}
@Tuneit 可以这样直接设置kafka主题吧。 @KafkaListener(topics = "${kafka.topic.helloworld}")
application.properties kafka.topic.helloworld=