Search code examples
springscalaapache-kafkaspring-kafkaspring-el

How do I use Spring Expression Language for an Array in an annotation with 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()}")
  }

}

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

Solution

  • 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.