Deploy Google Guava Hashmultimap with Spring

Can I provide an example of creation Multimap<String, String>using Spring?

I am curious to see how this will be done in the application context XML file.

+3
source share
1 answer

Google Collections is deprecated in favor of Guava , so I will answer about Guava.

I will use this Bean class:

public class Bean{
    private Multimap<String, String> map;
    public void setMap(Multimap<String, String> map){
        this.map = map;
    }
}

The only Guava Multimap factory method you can easily connect to (with XML only) is the method Multimaps.forMap(existingMap). Here's the XML:

<bean class="foo.bar.Bean">
    <property name="map">
        <bean class="com.google.common.collect.Multimaps"
            factory-method="forMap">
            <constructor-arg>
                <bean class="java.util.HashMap" />
            </constructor-arg>
        </bean>
    </property>
</bean>

Supplier Multimaps, Java-. Supplier, Spring FactoryBean:

public class SupplierFactoryBean<T> extends AbstractFactoryBean<Supplier<T>>{

    private final Class<T> type;
    private final Supplier<T> supplier;

    public SupplierFactoryBean(final Class<T> type){
        this.type = type;
        this.supplier = new Supplier<T>(){
            @Override
            public T get(){
                try{
                    return type.newInstance();
                } catch(final Exception e){
                    throw new IllegalStateException(e);
                }
            }
        };
    }

    @Override
    public Class<?> getObjectType(){ return type; }

    @Override
    protected Supplier<T> createInstance() throws Exception{
        return supplier;
    }
}

( FactoryBean, Spring . , .)

. :

<bean class="foo.bar.Bean">
    <property name="map">
        <bean class="com.google.common.collect.Multimaps"
            factory-method="newSetMultimap">
            <constructor-arg>
                <bean class="java.util.HashMap" />
            </constructor-arg>
            <constructor-arg>
                <bean class="foo.bar.SupplierFactoryBean">
                    <constructor-arg value="java.util.TreeSet" />
                </bean>
            </constructor-arg>
        </bean>
    </property>
</bean>

factory. Spring: 3.3.2.2 factory p >

+7

Source: https://habr.com/ru/post/1784015/


All Articles