将动态属性列表读入弹簧管理的bean [英] reading a dynamic property list into a spring managed bean

查看:140
本文介绍了将动态属性列表读入弹簧管理的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索,但找不到这些步骤。我希望我缺少一些明显的东西。



我有一个包含以下内容的属性文件:

 机器= A,B 

我有另一个文件,机器元素中不同数量的成员如下:

  machines = B,C,D 


如下所示:

 < property name =machinesvalue = $ {机}/> 

其中机器是我的java代码中的数组或列表。我可以定义它,但是我想知道如何做到这一点。



基本上我宁愿春天做解析,并将每个值粘贴到一个列表元素而不是我必须写入读取完整机器字符串的东西,并且自己解析(使用逗号分隔符)将每个值放入数组或列表中。有没有一个简单的方法来做到这一点我失踪了?

解决方案

你可能想看看Spring的StringUtils类。它有许多有用的方法将逗号分隔列表转换为Set或String数组。您可以使用任何这些实用程序方法,使用Spring的工厂方法框架,将解析的值注入到您的bean中。以下是一个例子:

 < property name =machines> 
< bean class =org.springframework.util.StringUtilsfactory-method =commaDelimitedListToSet>
< constructor-arg type =java.lang.Stringvalue =$ {machines}/>
< / bean>
< / property>

在此示例中,机器的值从属性文件加载。



如果现有的实用程序方法不能满足您的需要,则创建自己的实用程序非常简单。这种技术允许您执行任何静态实用程序方法。


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?

解决方案

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:

<property name="machines">
    <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">
        <constructor-arg type="java.lang.String" value="${machines}"/>
    </bean>
</property>

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.

这篇关于将动态属性列表读入弹簧管理的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆