将动态属性列表读入 Spring 托管 bean
我一直在寻找但找不到这些步骤。我希望我遗漏了一些明显的东西。
我有一个包含以下内容的属性文件:
machines=A,B
我有另一个类似的文件,但机器元素中有不同数量的成员,如下所示:
machines=B,C,D
我的问题是如何将此可变长度机器变量加载到我的 spring 配置中的 bean 中以一般的方式?
像这样的东西:
<property name="machines" value="${machines}"/>
其中machines是我的java代码中的数组或列表。如果我能弄清楚如何做到这一点,我可以按照我想要的方式定义它。
基本上我宁愿让 spring 进行解析并将每个值粘贴到列表元素中,而不是我必须编写一些读取完整机器字符串的内容并自己进行解析(使用逗号分隔符)以将每个值放入数组中或列出。有没有一种简单的方法可以做到我所缺少的?
I've been searching but cannot find these steps. I hope I'm missing something obvious.
I have a properties file with the following contents:
machines=A,B
I have another file like that but having a different number of members in the machines element like this:
machines=B,C,D
My question is how do I load this variable-length machines variable into a bean in my spring config in a generic way?
something like this:
<property name="machines" value="${machines}"/>
where machines is an array or list in my java code. I can define it however I want if I can figure out how to do this.
Basically I'd rather have spring do the parsing and stick each value into a list element instead of me having to write something that reads in the full machines string and do the parsing myself (with the comma delimiter) to put each value into an array or list. Is there an easy way to do this that I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可能想看一下 Spring 的 StringUtils 类。它有许多有用的方法将逗号分隔的列表转换为 Set 或 String 数组。您可以使用任何这些实用方法,通过 Spring 的工厂方法框架,将解析后的值注入到您的 bean 中。下面是一个示例:
在此示例中,“machines”的值是从属性文件加载的。
如果现有的实用方法不能满足您的需求,那么创建您自己的方法非常简单。该技术允许您执行任何静态实用程序方法。
You may want to take a look at Spring's StringUtils class. It has a number of useful methods to convert a comma separated list to a Set or a String array. You can use any of these utility methods, using Spring's factory-method framework, to inject a parsed value into your bean. Here is an example:
In this example, the value for 'machines' is loaded from the properties file.
If an existing utility method does not meet your needs, it is pretty straightforward to create your own. This technique allows you to execute any static utility method.
Spring EL 让一切变得更容易。
Java:
上下文:
Spring EL makes easier.
Java:
Context:
如果你将属性“machines”设置为一个字符串数组,那么 spring 会自动为你做这件事
If you make the property "machines" a String array, then spring will do it automatically for you
从 Spring 3.0 开始,还可以使用 @Value 注释读取值列表。
属性文件:
Java代码:
Since Spring 3.0, it is also possible to read in the list of values using the @Value annotation.
Property file:
Java code:
您可以直接将值注入到列表中,而无需样板代码。(Spring 3.1+)
通过在配置中创建以下两个实例来为属性文件中的键“machines=B,C,D”。
这些也将涵盖所有基于单独的分割和空白修剪。
You can inject the values to the list directly without boilerplate code.(Spring 3.1+)
for the key "machines=B,C,D" in the properties file by creating following two instance in your configuration.
Those will cover all the separate based split and whitespace trim as well.