4

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

Federico Gatti
  • 535
  • 1
  • 9
  • 22
  • You should try @ConfigurationProperties annotation to fetch yml configuration data. – GauravRai1512 Nov 16 '18 at 11:33
  • @GauravRai1512 and after that? How I can use the fetched properties and inject it in the **@GetMapping** annotation? You cannot inject variable in the annotation, only constant – Federico Gatti Nov 16 '18 at 11:38

2 Answers2

4

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");
}
Sukhpal Singh
  • 2,130
  • 9
  • 20
3

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

Mykhailo Moskura
  • 2,073
  • 1
  • 9
  • 20
  • Thank you, your second solutions work fine with a specific number of url in the properties, I'm searching for a dynamic solution for any number of values inside the array – Federico Gatti Nov 16 '18 at 11:55