user2346013
user2346013

Reputation: 101

spring: usage key of map in Spel expressions

I want to use my properties in my spel expression, for example in Kafka listener description

@KafkaListener(topics = "#{'${mymap.keys}'}",
        containerFactory = "kafkaListenerContainerFactory",
        autoStartup = "${kafka.enable}",
        concurrency = "1")

Here is my application.yaml

mymap:
{
"key1": "value1",
"key2": "value1",
}

Is it possible to use key from my map from yaml file? I have tried many similar ways to use keys from my map, but all of them don't work

Upvotes: 0

Views: 568

Answers (1)

Gary Russell
Gary Russell

Reputation: 174664

This works:

myprops:
  mymap:
    key1: value1
    key2: value1
@ConfigurationProperties(prefix = "myprops")
public class Props {

    private final Map<String, String> mymap;

    public Props(Map<String, String> mymap) {
        this.mymap = mymap;
    }

    public Map<String, String> getMymap() {
        return this.mymap;
    }

}
@SpringBootApplication
@EnableConfigurationProperties(Props.class)
public class So69705322Application {

    public static void main(String[] args) {
        SpringApplication.run(So69705322Application.class, args);
    }

    @KafkaListener(id = "so69705322",
            topics = "#{@'myprops-com.example.demo.Props'.mymap.keySet.toArray(new String[0])}")
    void listen(String in) {
        System.out.println(in);
    }

}

Notice how the bean name for the properties is contructed.

Upvotes: 1

Related Questions