How do I use Spring Expression Language for an Array in an annotation with Scala

别来无恙 提交于 2020-02-08 02:32:21

问题


I have a simple Scala project that looks like this...

@Configuration
public class CommonConfiguration{
    ...
    @Value("${spring.kafka.topic}")
    public String topic;
    ...
}
@Service
class KafkaService @Autowired()(producer: KafkaTemplate[String, Array[Byte]], config: CommonConfiguration){

  def sendMessage(msg: String): Unit = {
    println(s"Writing the message $msg ${config.topic}")
    producer.send(config.topic, msg.getBytes());
  }

  @KafkaListener(id="test", topics="#{'${spring.kafka.topic}'.split(',')}")
  def consume(record: ConsumerRecord[String, String]): Unit = {
    System.out.println(s"Consumed Strinsg Message : ${record.value()}")
  }

}

This gives me the error...

KafkaService.scala:26: error: type mismatch;
[ERROR]  found   : String("#{\'${spring.kafka.topic}\'.split(\',\')}")
[ERROR]  required: Array[String]
[ERROR]   @KafkaListener(id="test", topics= "#{'${spring.kafka.topic}'.split(',')}")

I tried using #{'${spring.kafka.topic}'.split(',')} per this suggestion but I can't get it to work. The producer gets the topic just fine. How do I use Spring Expression Language with Scala?

Here is the working Java Version...

@Service
public class KafkaJavaService {
    @KafkaListener(id="test", topics="#{'${spring.kafka.topic}'.split(',')}")
    public void consume(ConsumerRecord<String, String> record){
        System.out.println("Consumed String Message : "+record.value())
    }
}

回答1:


According to this question, it looks like topics = Array("...") should work.

Reading the @RequestMapping documentation : http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestMapping.html

It accepts a String array parameter for its path mapping.

So this works using java :

@RequestMapping("MYVIEW")

but in scala I need to use :

@RequestMapping(Array("MYVIEW"))

The scala version makes sense as the annotation expects a String array. But why does above work in java, should it not give a compile time error ?

EDIT

This is also not technically the same thing because the other way I could use a CSV. Even if the worked it would be a 1 string array unless the Array constructor does some fancyness.

It shouldn't make a difference; as I said, if an expression in an element of the String[] resolves to a String[], we recursively break it apart (flatten it). See here and here.

Try setting a breakpoint in those methods; I don't have Scala installed otherwise I'd take a look.



来源:https://stackoverflow.com/questions/60065408/how-do-i-use-spring-expression-language-for-an-array-in-an-annotation-with-scala

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