2

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)}")
Artem Bilan
  • 113,505
  • 11
  • 91
  • 118
TuneIt
  • 572
  • 2
  • 9
  • 20
  • In future, you MUST provide more information than "fails to work"; you should provide the error message and stack trace. However, your problems are obvious this time. – Gary Russell Mar 12 '18 at 12:59

3 Answers3

2

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);
  }
TuneIt
  • 572
  • 2
  • 9
  • 20
1

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.

Artem Bilan
  • 113,505
  • 11
  • 91
  • 118
  • Right - SpEL is NOT JAVA - it's the Spring Expression __Language__; it doesn't have Lambdas; however, you __can__ register lambdas as SpEL Functions; see [this answer](https://stackoverflow.com/questions/48840190/spring-expression-language-java-8-foreach-or-stream-on-list/48842973#48842973). – Gary Russell Mar 12 '18 at 12:58
  • + even if lambda were supported access to static method of Arrays should be written `T(java.util.Arrays).asList...` – p3consulting Apr 25 '18 at 06:01
-2

@Tuneit You can set the kafka topics directly like this it. @KafkaListener(topics = "${kafka.topic.helloworld}")

application.properties kafka.topic.helloworld=

Rohit
  • 22
  • 1