Java Spring:如何使用 @Value 注释注入内联字符串列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27390363/
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
Spring: how to inject an inline list of strings using @Value annotation
提问by Brice Roncace
How do I inject a list of string values using the @Value
annotation. I'm using Spring 4.1.2.
如何使用@Value
注释注入字符串值列表。我正在使用 Spring 4.1.2。
I've tried:
我试过了:
@Value(value = "top, person, organizationalPerson, user")
private List<String> userObjectClasses
and then based on the spring el documentation for inline lists:
然后基于内联列表的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.
这些尝试仅注入作为列表中唯一元素给出的值的字符串文字。
EDIT
编辑
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"});
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):
过去,我使用 spring 的 XML 配置来连接 bean,在这种情况下我可以这样做(假设 bean 有一个公共的userObjectClasses
属性设置器):
<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?
使用基于注释的配置时是否有类似的情况?
采纳答案by Yuri
list.of.strings=first,second,third
took from properties file for e.g.
list.of.strings=first,second,third
从属性文件中获取例如
Then using SpEL:
然后使用SpEL:
@Value("#{'${list.of.strings}'.split(',')}")
private List<String> list;
EDIT
编辑
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 @PostConstructin order to initialize some fields.
那么我认为您不需要对此类任务使用注释。您可以像您提到的那样或在@PostConstruct中完成所有工作以初始化某些字段。