Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@GetMapping with array parameters by application.yml

I have developed this @GetMapping RestController and all works fine

@GetMapping(path = {"foo", "bar"})
public ResponseEntity<String> foobar() {
    return ResponseEntity.ok("foobar");
}

now I want externalize the values inside the path array using my application.yml file,so I writed

url:
  - foo
  - bar

and I modified my code in order to use it, but it doesn't work in this two different ways

@GetMapping(path = "${url}")
public ResponseEntity<String> foobar() {
    return ResponseEntity.ok("foobar");
}

@GetMapping(path = {"${url}"})
public ResponseEntity<String> foobar() {
    return ResponseEntity.ok("foobar");
}

I don't understand if the application properties are not correctly formatted or I need to use the SpEL (https://docs.spring.io/spring/docs/3.0.x/reference/expressions.html.

I also want that the code is dynamic according to the application.yml properties, so if the url values increase or decrease the code must still work.

I'm using Springboot 1.5.13

like image 885
Federico Gatti Avatar asked Mar 05 '23 01:03

Federico Gatti


2 Answers

You can't bind YAML list to array or list here. For more information see: @Value and @ConfigurationProperties behave differently when binding to arrays

However, you can achieve this by specifying regular expression in yml file like:

url: '{var:foo|bar}'

And then you can use it directly in your controller:

@GetMapping(path = "${url}")
public ResponseEntity<String> foobar() {
    return ResponseEntity.ok("foobar");
}
like image 76
Sukhpal Singh Avatar answered Mar 20 '23 15:03

Sukhpal Singh


You can use in your controller

@GetMapping(path = "${url[0]}")
public ResponseEntity<String> foobar() {
    return ResponseEntity.ok("foobar");
}

@GetMapping(path = {"${url[1]}"})
public ResponseEntity<String> foobar() {
    return ResponseEntity.ok("foobar");
}

Or you can do in this way:

@GetMapping(path = {"${url[0]}","${url[1]}"})
public ResponseEntity<String> foobar() {
    return ResponseEntity.ok("foobar");
}

I think this is helpful

like image 43
Mykhailo Moskura Avatar answered Mar 20 '23 15:03

Mykhailo Moskura