我想在.properties文件中有一个值列表,即:

my.list.of.strings=ABC,CDE,EFG

并直接在我的类中加载它,即:

@Value("${my.list.of.strings}")
private List<String> myList;

据我所知,另一种方法是将它放在spring配置文件中,并将其作为bean引用加载(如果我错了请纠正我),即

<bean name="list">
 <list>
  <value>ABC</value>
  <value>CDE</value>
  <value>EFG</value>
 </list>
</bean>

但是有没有办法做到这一点呢?使用.properties文件? ps:如果可能的话,我想这样做没有任何自定义代码。


当前回答

以上答案都是正确的。但是您可以在一行中实现这一点。 请尝试下面的声明,您将在String列表中获得所有逗号分隔的值。

private @Value("#{T(java.util.Arrays).asList(projectProperties['my.list.of.strings'])}") List<String> myList;

您还需要在xml配置中定义以下行。

<util:properties id="projectProperties" location="/project.properties"/>

只需替换属性文件的路径和文件名。这样就可以开始了。:)

希望这对你有所帮助。欢呼。

其他回答

你是否考虑过@Autowireding构造函数或在body中使用setter和String.split() ?

class MyClass {
    private List<String> myList;

    @Autowired
    public MyClass(@Value("${my.list.of.strings}") final String strs) {
        myList = Arrays.asList(strs.split(","));
    }

    //or

    @Autowired
    public void setMyList(@Value("${my.list.of.strings}") final String strs) {
        myList = Arrays.asList(strs.split(","));
    }
}

我倾向于用这些方法中的一种来进行自动装配,以增强代码的可测试性。

通过指定my.list.of。字符串=ABC,CDE,EFG在.properties文件和使用

@ value (" $ {my.list.of.strings} ") private String[] myString;

你可以得到字符串的数组。并使用CollectionUtils。addAll(myList, myString),你可以得到字符串列表。

考虑使用公共配置。它有内置的功能,以打破一个条目在属性文件数组/列表。结合SpEL和@Value应该会给你想要的


按照要求,这是你需要的(没有真正尝试过代码,可能会有一些错误,请原谅我):

在Apache Commons Configuration中,有PropertiesConfiguration。它支持将分隔字符串转换为数组/列表的特性。

例如,如果您有一个属性文件

#Foo.properties
foo=bar1, bar2, bar3

用下面的代码:

PropertiesConfiguration config = new PropertiesConfiguration("Foo.properties");
String[] values = config.getStringArray("foo");

会给你一个字符串数组["bar1", "bar2", "bar3"]

要和Spring一起使用,在你的app context xml中有这个:

<bean id="fooConfig" class="org.apache.commons.configuration.PropertiesConfiguration">
    <constructor-arg type="java.lang.String" value="classpath:/Foo.properties"/>
</bean>

在你的春豆里加入这个:

public class SomeBean {

    @Value("fooConfig.getStringArray('foo')")
    private String[] fooArray;
}

我相信这是可行的:P

我使用Spring Boot 2.2.6

我的属性文件:

usa.big.banks= JP Morgan, Wells Fargo, Citigroup, Morgan Stanley, Goldman Sachs

我的代码:

@Value("${usa.big.banks}")
    private List<String> bigBanks;

@RequestMapping("/bigbanks")
    public String getBanks() {
        System.out.println("bigBanks = " + bigBanks);
        return bigBanks.toString();
    }

它运行正常

这个问题的答案

@Value("#{'${my.list.of.strings}'.split(',')}") 
private List<String> myList; 

对逗号分隔的值按预期工作。 为了处理null(当属性未指定时),添加默认值(':'在属性名之后)为空字符串,如下所示:

@Value("#{'${my.list.of.strings: }'.split(',')}")