Thursday, March 19, 2015

Load properties into a guava ImmutableMap with Spring

Create your props file (here called secret-identities.properties):


Clark\ Kent = Superman
Bruce\ Wayne = Batman
Kit\ Walker = The Phantom

Note that by definition keys in .properties files cannot contain spaces.  So you must escape them with a '\'

In your Spring configuration:

<bean id="mapProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="ignoreResourceNotFound" value="true"/>
    <property name="fileEncoding" value="UTF-8"/>
    <property name="locations">
        <list>
            <value>classpath:secret-identites.properties</value>
        </list>
    </property>
</bean>

<bean id="secretIdentityMap" class="com.google.common.collect.ImmutableMap" factory-method="copyOf">
    <constructor-arg ref="mapProperties"/>
</bean>


Now you can get a fully injected ImmutableMap in your code:

@Autowired
private ImmutableMap<String, String> secretIdentityMap;


Thanks to Stackoverflow for inspiration!

No comments:

Post a Comment