Spring:如何使用@Value注释注入内联字符串列表 [英] Spring: how to inject an inline list of strings using @Value annotation
问题描述
如何使用 @Value
注释注入字符串值列表。我正在使用Spring 4.1.2。
How do I inject a list of string values using the @Value
annotation. I'm using Spring 4.1.2.
我试过:
@Value(value = "top, person, organizationalPerson, user")
private List<String> userObjectClasses
然后基于内联列表的spring el文档:
@Value(value = "{top, person, organizationalPerson, user}")
private List<String> userObjectClasses
这些尝试只注入给定值作为列表中唯一元素的字符串文字。
These attempts only inject a string literal of the value given as the only element in the list.
编辑
在这种情况下,我希望能够简单对值进行硬编码而不是从属性文件中读取。这种方法看起来不那么臭:
In this case, I'd like to be able to simply hard-code the values rather than read from a property file. This approach seems a little less smelly than:
private List<String> userObjectClasses = Arrays.asList(new String[] {"top", "person", "organizationalPerson", "user"});
过去,我使用spring的XML配置来连接bean,在这种情况下我可以做(假设bean有 userObjectClasses
属性的公共setter):
In the past, I've used spring's XML configuration to wire up beans, and in that case I could do (assuming the bean had a public setter for the userObjectClasses
property):
<property value="userObjectClass">
<list>
<value>top</value>
<value>person</value>
<value>organizationalPerson</value>
<value>user</value>
</list>
</property>
使用基于注释的配置时是否存在类似内容?
Is there an analog to this when using annotation based configuration?
推荐答案
list.of.strings =第一,第二,第三
从属性文件中获取,例如
list.of.strings=first,second,third
took from properties file for e.g.
然后使用 SpEL :
@Value("#{'${list.of.strings}'.split(',')}")
private List<String> list;
编辑
然后我认为你不需要为这类任务使用注释。您可以完成所有工作,就像您已经下载或 @PostConstruct 为了初始化一些字段。
Then I don't think that you need to use annotation for such type of tasks. You could do all work just like you've menitioned or in the @PostConstruct in order to initialize some fields.
这篇关于Spring:如何使用@Value注释注入内联字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!