如何在Spring Bean中使用.properties文件中的值初始化一个集合

3
我是一个有用的助手,可以翻译文本。
我有一个Spring Bean(我们称其为MagicBean),其中一个属性是HashSet。
我知道如何初始化这样的集合:
<bean id="mySet" class="org.springframework.beans.factory.config.SetFactoryBean">
    <property name="targetSetClass" value="java.util.HashSet"/>
    <property name="sourceSet">
        <set>
            <value>Value 1</value>
            <value>Value 2</value>
            <value>Value 3</value>
        </set>
    </property>
</bean>

<bean id="magicBean" class="MagicBean">
    <property name="mySet" ref="mySet"/>
</bean>

有没有一种方法可以使用.properties文件中的值来设置集合中的值,而不是在xml中硬编码这些值?
更新1: 由于我在不同的环境中可能会有不同数量的集合值,因此在xml中使用硬编码的集合将无法工作。这就是为什么我需要以某种方式从属性文件中获取这些值。
更新2: 我想出了一种快速且简单的方法,即将所有值列在.properties文件中的一个字符串中,然后将此值设置为MagicBean。然后在Java代码中解析此字符串。 有更好的想法吗?
2个回答

1

您可以使用:

<value>${my.set.value1}/value>

并在属性文件中设置值:

my.set.value1=Value1

但是我不知道我会有多少个值。在不同的环境中,这个集合可能会有不同数量的值。 - 0x56794E
那么你如何在xml中声明它? - BobTheBuilder
啊,我之前评论的意思是我想表达的。在不同的环境中,这个集合可能有不同数量的值,因此在xml中使用硬编码的集合是行不通的。这就是为什么我需要从属性文件中获取这些值的原因。 - 0x56794E
好的,我看了一下这些关于条件性Spring配置的问题(不是针对特定设置)。链接在这里:https://dev59.com/PHA75IYBdhLWcg3w6Nr8 和 https://dev59.com/YGw05IYBdhLWcg3w_Guw。 - BobTheBuilder

1
尝试类似于这样的东西。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util.xsd
                           ">
    <bean class="B1">
        <property name="Props">
            <util:properties location="classpath:test.properties" />
        </property>
    </bean>
</beans>

这是B1。
class B1 {
    public void setProps(Properties props) {
        ...
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接