How to bind a string array of properties in Spring?

匿名 (未验证) 提交于 2019-12-03 01:38:01

问题:

I have the following in my application.properties file

some.server.url[0]=http://url some.server.url[1]=http://otherUrl 

How do I refer to the array of properties using the @Value anotation inside a @Bean method?

I am using Java 6 with Tomcat 7 and Spring boot 1.4

回答1:

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'



回答2:

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



回答3:

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;     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!