本文介绍了如何在Scala批注中对数组使用Spring Expression Language的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Scala项目,看起来像这样...

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

}

这给了我错误...

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(',')}")

我尝试根据建议,但我无法使其正常工作.制片人得到的话题很好.如何在Scala中使用Spring Expression Language?

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?

这是有效的Java版本...

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

推荐答案

根据,看起来 topics = Array(" ...)应该可以工作.

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

它接受String数组参数作为其路径映射.

It accepts a String array parameter for its path mapping.

所以这可以使用java进行工作:

So this works using java :

@RequestMapping("MYVIEW")

但是在scala中,我需要使用:

but in scala I need to use :

@RequestMapping(Array("MYVIEW"))

scala版本很有意义,因为注释需要一个String数组.但是,为什么上面的代码在Java中起作用,它不应该给出编译时错误吗?

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 ?

编辑

这不应该有所作为;如我所说,如果 String [] 元素中的表达式解析为 String [] ,我们将递归地将其拆分(展平).参见此处此处.

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.

尝试在这些方法中设置断点;我没有安装Scala,否则请看一看.

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

这篇关于如何在Scala批注中对数组使用Spring Expression Language的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 04:09