Need help in using SPEL in Annotation Value?

房东的猫 提交于 2019-12-08 10:12:10

问题


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)}")

回答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.




回答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);
  }


来源:https://stackoverflow.com/questions/49228492/need-help-in-using-spel-in-annotation-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!