如何在 Spring 中绑定属性的字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38986127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:10:53  来源:igfitidea点击:

How to bind a string array of properties in Spring?

springspring-mvcspring-boot

提问by SebS

I have the following in my application.properties file

我的 application.properties 文件中有以下内容

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?

如何在 @Bean 方法中使用 @Value 注释来引用属性数组?

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

我在 Tomcat 7 和 Spring boot 1.4 中使用 Java 6

采纳答案by user3567935

Follow these steps

按着这些次序

1) @Value("${some.server.url}") private List urls;

1) @Value("${some.server.url}") 私有列表网址;

2) @ConfigurationProperties("some.server") public class SomeConfiguration {

2) @ConfigurationProperties("some.server") public class SomeConfiguration {

3) You should have getter and setter for instance variable 'urls'

3)你应该有getter和setter实例变量'urls'

回答by Aman Tuladhar

I was also having the same problem as you mentioned and it seems using index form on application.propertieswas not working for me either.

我也遇到了与您提到的相同的问题,似乎使用索引表单对application.properties我也不起作用。

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

@Value("${some.server.url}")
private String[] urls ;

Springautomatically splitsthe String with commaand return you an Array. AFAIKthis was introduced in Spring 4+

Spring自动用逗号分割String并返回一个Array。这是在AFAIKSpring 4+

If you don't want comma (,)as seperator you have to use SpELlike below.

如果您不想comma (,)作为分隔符,则必须使用如下所示的SpEL

@Value("#{'${some.server.url}'.split(',')}")
private List<String> urls;

where split()accepts the seperator

wheresplit()接受分隔符

回答by Shawn Clark

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:

您还可以使用配置类并将 bean 注入其他类:

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