Define guava HashBasedTable/Table in spring xml config

霸气de小男生 提交于 2019-12-23 02:31:39

问题


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>

回答1:


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>



回答2:


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


来源:https://stackoverflow.com/questions/23897335/define-guava-hashbasedtable-table-in-spring-xml-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!