Tried below SPEL expression, but it fails to work. Need help!
@KafkaListener(topics = "#{Arrays.asList(${kafka.topic.helloworld}.split(',')).stream().map(p -> p+envSuffix).toArray(String[]::new)}")
Tried below SPEL expression, but it fails to work. Need help!
@KafkaListener(topics = "#{Arrays.asList(${kafka.topic.helloworld}.split(',')).stream().map(p -> p+envSuffix).toArray(String[]::new)}")
Solution is: One of the way to add lambda into annotation is as follows: In the KafkaReceiver class's method -
@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);
}
First of all I see that ${kafka.topic.helloworld}
has to be wrapped to the ''
, just because property-placeholder works first and then SpEL will treat the result a an active variable. For example you have there, foo,bar,baz
. How does it look in Java? Nothing more than wrong code. But when it is "foo,bar,baz"
, the language knows that it is a String. The same with SpEL - it must be like '${kafka.topic.helloworld}'
.
But that's not all. I'm afraid SpEL doesn't support lambdas. I suggest you to have some utility bean, which you could call from this expression like:
@KafkaListener(topics = "myUtility.parseTopics('${kafka.topic.helloworld}')")
And all that hard conversion logic will be done in the parseTopics()
utility Java method.
There is a Collection Projection feature in SpEL, but you still would need to do arrays manipulations here and there.
@Tuneit You can set the kafka topics directly like this it. @KafkaListener(topics = "${kafka.topic.helloworld}")
application.properties kafka.topic.helloworld=