问题描述
是否可以提供使用Spring创建Multimap<String, String>
的示例?
Is it possible to provide an example of creating a Multimap<String, String>
using Spring?
我很好奇如何在应用程序上下文XML文件中完成此操作.
I am curious in looking at how it would be done in the application context XML file.
推荐答案
Google Collections is deprecated in favor of Guava, so I will answer regarding Guava.
我将使用此Bean类:
I will use this Bean class:
public class Bean{
private Multimap<String, String> map;
public void setMap(Multimap<String, String> map){
this.map = map;
}
}
Multimaps.forMap(existingMap)
方法.这是XML:
The only Guava Multimap factory method you can easily wire (with XML only) is the Multimaps.forMap(existingMap)
method. 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
类,您将必须将Suppliers创建为Java类.如果只想使用基元实例化Supplier
,则可以将其创建为Spring FactoryBean
:
If you want one of the more complicated Supplier
-based methods in the Multimaps
class, you will have to create the Suppliers as Java Classes. If you just want a primitive instantiating Supplier
, you can create that as a 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的Supplier类,Spring的用法保持不变.只需确保它为每次调用返回一个新实例即可.)
(You may also model the above as a Supplier class without a FactoryBean, the Spring usage remains the same. Just make sure it returns a new instance for every call.)
现在,您可以连接更复杂的方法.示例:
Now you can wire the more complicated methods. Example:
<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>
以上两个示例都使用静态工厂方法.这是Spring参考中的相应章节: 3.3.2.2使用静态工厂方法实例化
Both examples above use static factory methods. Here's the corresponding chapter in the Spring Reference: 3.3.2.2 Instantiation with a static factory method
这篇关于使用Spring注入Google Guava Hashmultimap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!