How to bind a string array of properties in Spring?
You can use a collection.
@Value("${some.server.url}")
private List<String> urls;
You can also use a configuration class and inject the bean into your other class:
@Component
@ConfigurationProperties("some.server")
public class SomeConfiguration {
private List<String> url;
public List<String> getUrl() {
return url;
}
public void setUrl(List<String> url) {
this.url = url;
}
}
Follow these steps
1) @Value("${some.server.url}") private List urls;
2) @ConfigurationProperties("some.server") public class SomeConfiguration {
3) You should have getter and setter for instance variable 'urls'
I was also having the same problem as you mentioned and it seems using index form on application.properties
was not working for me either.
To solve the problem I did something like below
some.server.url = url1, url2
Then to get the those properties I simply use @Value
@Value("${some.server.url}")
private String[] urls ;
Spring automatically splits the String with comma and return you an Array. AFAIK this was introduced in Spring 4+
If you don't want comma (,)
as seperator you have to use SpEL like below.
@Value("#{'${some.server.url}'.split(',')}")
private List<String> urls;
where split()
accepts the seperator