开发者

Automatically wiring multiple arrays from properties file with Spring

I have a class like this:

class MyClass {
    Map<String, String[]> arrays; 
    public void setArrays(Map<String, String[]> arrays)
    {
        this.arrays = arrays;
    }
    public String[] getArray(String key)
    {
        return arrays.get(key);
    }
}    

The values are provided from a properties file like this:

# my.properties
arrays.arrayOne=a,b开发者_Go百科,c
arrays.arrayTwo=d,e,f

Using spring I can wire the property this way:

<property name="arrays">
    <map>
        <entry key="arrayOne" value="${arrays.arrayOne}"/>
        <entry key="arrayTwo" value="${arrays.arrayTwo}"/>
    </map>
</property>

Now, this works but I have to manually edit the wiring every time I add a new entry into the properties file. Is there a better way to do this?


I solved my problem using PropertyOverrideConfigurer:

<!-- applicationContext.xml -->
<bean id="myBean" class="com.myapp.MyClass">
    <property name="arrays">
        <map/>
    </property>
</bean>

<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
    <property name="location" value="classpath:my.properties"/>
</bean>

(I could also init the map directly in my class to make the code more concise)

# my.properties
myBean.arrays[arrayOne]=a,b,c
myBean.arrays[arrayTwo]=d,e,f

That's all it takes, and spring populates the map correctly, additions to the properties file being updated without further config. Calling getArray("arrayOne") on my bean returns an array of strings {"a", "b", "c"} as intended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜