我想在.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:如果可能的话,我想这样做没有任何自定义代码。


当前回答

注意值中的空格。我可能错了,但我认为逗号分隔列表中的空格没有使用@Value和Spel截断。列表

foobar=a, b, c

会被读入一个字符串列表吗

"a", " b", " c"

在大多数情况下,您可能不想要空格!

表达式

@Value("#{'${foobar}'.trim().replaceAll(\"\\s*(?=,)|(?<=,)\\s*\", \"\").split(',')}")
private List<String> foobarList;

会给你一个字符串列表

"a", "b", "c".

正则表达式删除逗号前面和后面的所有空格。值中的空格不会被删除。所以

foobar = AA, B B, CCC

应该得到的值

"AA", "B B", "CCC".

其他回答

考虑使用公共配置。它有内置的功能,以打破一个条目在属性文件数组/列表。结合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 EL:

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

假设你的属性文件正确加载如下:

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

我更喜欢的方式(特别是字符串)是以下一个:

admin.user={'Doe, John','Headroom, Max','Mouse, Micky'}

和使用

@Value("#{${admin.user}}")
private List<String> userList;

通过这种方式,还可以在参数中包含逗号。它也适用于集合。

从Spring 3.0开始,你可以添加一行像

<bean id="conversionService" 
    class="org.springframework.context.support.ConversionServiceFactoryBean" />

到你的applicationContext.xml(或者你配置的地方)。 正如Dmitry Chornyi在评论中指出的那样,基于Java的配置看起来是这样的:

@Bean public ConversionService conversionService() {
    return new DefaultConversionService();
}

这将激活新的配置服务,该服务支持将字符串转换为集合类型。 如果您不激活这个配置服务,Spring将依赖其遗留属性编辑器作为配置服务,它不支持这种类型的转换。

转换为其他类型的集合也可以:

@Value("${my.list.of.ints}")
private List<Integer> myList

会不会跟线条一样

 my.list.of.ints= 1, 2, 3, 4

这里的空白没有问题,ConversionServiceFactoryBean会处理它。

看到http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/ core-convert-Spring-config

在Spring应用程序中,通常为每个Spring容器(或ApplicationContext)配置一个ConversionService实例。该ConversionService将被Spring拾取,然后在框架需要执行类型转换时使用。 […] 如果没有向Spring注册ConversionService,则使用原始的基于properteditor的系统。

在我的情况下,一个整数列表的工作:

@Value("#{${my.list.of.integers}}")
private List<Integer> listOfIntegers;

属性文件:

my.list.of.integers={100,200,300,400,999}