I'm trying to create and populate a guava HashBasedTable
in spring xml config file but I haven't been able to.
My table looks like this:
Table<String, Foo, Bar> myTable;
And I've tried this in my xml but don't know how put new value into the table:
<property name="myTable">
<bean class="com.google.common.collect.HashBasedTable" factory-method="create">
<!--- how do I insert value in here??? -->
</bean>
</property>
If you want to do this exclusively in xml, it's a bit tricky: I see guava doesn't offer too many options for putting values in that Table.
There is an approach, but it's weird for more than one insert:
<bean id="myTable" class="com.google.common.collect.HashBasedTable" factory-method="create" />
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<ref local="myTable" />
</property>
<property name="targetMethod">
<value>put</value>
</property>
<property name="arguments">
<list>
<value>1</value>
<value>1</value>
<value>value</value>
</list>
</property>
</bean>
If you have not to use exclusively xml, you can use some Java to make your configuration a little more readable.
You can create an Utility method:
public class Utils {
public static Table tableFromMap(Map<Object, Map<Object, Object>> map){
Table ret = null;
if(map != null){
ret = HashBasedTable.create();
for(Object k1 : map.keySet()){
if(map.get(k1) != null){
for(Object k2 : map.get(k1).keySet()){
ret.put(k1, k2, map.get(k1).get(k2));
}
}
}
}
return ret;
}
}
And add this to your configuration
<bean id="mytable" class="it.myproject.Utils" factory-method="tableFromMap">
<constructor-arg>
<util:map>
<entry key="A">
<util:map>
<entry key="B" value="C" />
<entry key="D" value="E" />
</util:map>
</entry>
</util:map>
</constructor-arg>
</bean>
Resulting in this table:
A | B | C
A | D | E