Dmytro Plekhotkin
Dmytro Plekhotkin

Reputation: 1993

How to store map in .properties file that is used by Spring project?

Is it the good idea to store map like that:

myMap=k1:v1,k2:v2,k3:v3

and then parse its value as Map object?

[Update] What is the best way to store map in properties file (as whole properties file or just part of it), and how to access that whole map (not just one key/value from the map)?

Upvotes: 0

Views: 1974

Answers (2)

Tap
Tap

Reputation: 6522

You should use the spring MapFactoryBean. Spring will give you map when you ask for the bean.

<bean id="myBean" class="org.springframework.beans.factory.config.MapFactoryBean">
    <property name="sourceMap">
        <map>
            <entry key="k1">
                <value>v1</value>
            </entry>
            <entry key="k2">
                <value>v2</value>
            </entry>
            <entry key="k3">
                <value>v3</value>
            </entry>
        </map>
    </property>
    <property name="targetMapClass" value="java.util.TreeMap"/>
</bean>

Upvotes: 0

Paul Whelan
Paul Whelan

Reputation: 16809

The Properties class implements Map Just define the properties bean like so:

<util:properties id="myMap" location="classpath:myMap.properties" />

then set a reference to myMap in your bean that needs the properties.

Upvotes: 1

Related Questions