[英]How to initialize a set in a spring bean using value from .properties file
我有一個spring bean(我們稱之為MagicBean
),它有一個HashSet<String>
作為它的一個屬性。
我知道如何初始化這樣的集合:
<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代碼中解析此字符串。 有什么好主意嗎?
您可以使用:
<value>${my.set.value1}/value>
並在屬性文件中設置值:
my.set.value1=Value1
嘗試這樣的事情
<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) {
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.