JSF & Java Blog

Discussion on Java and JSF, including Spring, Maven, Eclipse and Jenkins

Guava ImmutableMap Spring bean

0

I previously had some maps defined as Spring beans in my applicationContext.xml file. An example of a basic Map is shown below:

<util:map id="fuelType">
    <entry key="P" value="Petrol"/>
    <entry key="D" value="Diesel"/>
</util:map>

I wanted to make these all immutable and so Guava’s ImmutableMap seeemed the logical Map type to use. However, ImmutableMap is abstract so you can’t just do the following:

<util:map id="fuelType" map-class="com.google.common.collect.ImmutableMap">
    <entry key="P" value="Petrol"/>
    <entry key="D" value="Diesel"/>
</util:map>

Instead, thanks to help from Paul Reeves, you need to use the static method copyOf(Map<? extends K,? extends V> map). This can be done in Spring to create a ImmutableMap Spring bean like so:

<bean id="fuelType" class="com.google.common.collect.ImmutableMap" factory-method="copyOf">
	<constructor-arg>
		<util:map>
			<entry key="P" value="Petrol"/>
			<entry key="D" value="Diesel"/>
		</util:map>
	</constructor-arg>
</bean>

A great post covering Guava immutable collections compared against the java.util.Collections unmodifiable collections is on the Inspired by Actual Events blog.

So, what do you think ?

  • *