从属性文件中读取List并使用spring注释加载@Value

时间:2012-09-25 04:19:00

标签: java spring spring-properties

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

17 个答案:

答案 0 :(得分:363)

使用Spring EL:

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

假设您的属性文件已正确加载以下内容:

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

答案 1 :(得分:76)

从Spring 3.0开始,您可以添加类似

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

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

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

这会激活支持将String转换为Collection类型的新配置服务。 如果您不激活此配置服务,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,则使用原始的基于PropertyEditor的系统。

答案 2 :(得分:29)

通过在.properties文件中指定my.list.of.strings=ABC,CDE,EFG并使用

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

您可以获取字符串数组。使用CollectionUtils.addAll(myList, myString),您可以获得字符串列表。

答案 3 :(得分:22)

如果您正在阅读本文并且使用 Spring Boot ,则此功能还有1个选项

通常逗号分隔列表对于真实世界的用例非常笨拙 (有时甚至不可行,如果你想在你的配置中使用逗号):

email.sendTo=somebody@example.com,somebody2@example.com,somebody3@example.com,.....

使用 Spring Boot ,您可以像这样编写它(索引从0开始):

email.sendTo[0]=somebody@example.com
email.sendTo[1]=somebody2@example.com
email.sendTo[2]=somebody3@example.com

并使用它们:

@Component
@ConfigurationProperties("email")
public class EmailProperties {

    private List<String> sendTo;

    public List<String> getSendTo() {
        return sendTo;
    }

    public void setSendTo(List<String> sendTo) {
        this.sendTo = sendTo;
    }

}


@Component
public class EmailModel {

  @Autowired
  private EmailProperties emailProperties;

  //Use the sendTo List by 
  //emailProperties.getSendTo()

}



@Configuration
public class YourConfiguration {
    @Bean
  public EmailProperties emailProperties(){
        return new EmailProperties();
  }

}


#Put this in src/main/resource/META-INF/spring.factories
  org.springframework.boot.autoconfigure.EnableAutoConfiguration=example.compackage.YourConfiguration

答案 4 :(得分:18)

您是否考虑过@Autowired构造函数或者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(","));
    }
}

我倾向于选择以其中一种方式进行自动装配,以提高代码的可测试性。

答案 5 :(得分:7)

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

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

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

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

只需替换属性文件的路径和文件名即可。你很高兴。 :)

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

答案 6 :(得分:4)

如果您使用的是最新的Spring框架版本(我相信是Spring 3.1+),则不需要在SpringEL中使用这些字符串拆分的内容,

只需在Spring的Configuration类(带有Configuration注释的类)中添加PropertySourcesPlaceholderConfigurer和DefaultConversionService即可,例如

@Configuration
public class AppConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

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

和您的班级

@Value("${list}")
private List<String> list;

和属性文件中

list=A,B,C,D,E

没有DefaultConversionService,在将值注入字段时,只能将逗号分隔的String放入String数组,但是DefaultConversionService为您提供了一些方便的魔术,并将它们添加到Collection,Array等中。(检查实现是否您想进一步了解它)

有了这两个,它甚至可以处理所有多余的空格,包括换行符,因此您无需添加其他逻辑来修剪它们。

答案 7 :(得分:2)

你可以用这样的注释来做到这一点

 @Value("#{T(java.util.Arrays).asList('${my.list.of.strings:a,b,c}')}") 
    private List<String> mylist;

这里my.list.of.strings将从属性文件中挑选,如果不存在,那么将使用默认值a,b,c

并在您的属性文件中,您可以使用类似的内容

my.list.of.strings = d,E,F

答案 8 :(得分:2)

如果您使用的是Spring Boot 2,则无需任何其他配置即可直接使用。

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

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

答案 9 :(得分:1)

考虑使用Commons Configuration。它具有内置功能,可以将属性文件中的条目分解为数组/列表。与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一起使用,请在您的应用上下文中使用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

答案 10 :(得分:1)

小心值中的空格。我可能错了,但我认为逗号分隔列表中的空格不会使用@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".

答案 11 :(得分:1)

在我的整数列表的情况下,这可行:

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

属性文件:

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

答案 12 :(得分:1)

我的首选方式(特别是对于字符串)是以下方式:

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

并使用

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

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

答案 13 :(得分:1)

我正在使用Spring Boot 2.2.6

我的财产文件:

DEFAULT_DATE

我的代码:

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

效果很好

答案 14 :(得分:0)

如果使用属性占位符,则ser1702544示例将变为

@Value("#{myConfigProperties['myproperty'].trim().replaceAll(\"\\s*(?=,)|(?<=,)\\s*\", \"\").split(',')}") 

使用占位符xml:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
    <property name="properties" ref="myConfigProperties" />
    <property name="placeholderPrefix"><value>$myConfigProperties{</value></property>
</bean>    

<bean id="myConfigProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
     <property name="locations">
         <list>
                <value>classpath:myprops.properties</value>
         </list>
     </property>
</bean> 

答案 15 :(得分:0)

我认为这对于获取数组和剥离空格更简单:

@Value("#{'${my.array}'.replace(' ', '').split(',')}")
private List<String> array;

答案 16 :(得分:0)

答案

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

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

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