Thursday, March 19, 2015

Load properties into a guava ImmutableMap with Spring

Create your props file (here called

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">

<bean id="secretIdentityMap" class="" factory-method="copyOf">
    <constructor-arg ref="mapProperties"/>

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

private ImmutableMap<String, String> secretIdentityMap;

Thanks to Stackoverflow for inspiration!