简体   繁体   English

Spring使用自定义Comparator创建一个TreeMap并填充它

[英]Spring create a TreeMap with custom Comparator and populate it

In Java language, it's possible to create TreeMaps using our own Comparator class. 在Java语言中,可以使用我们自己的Comparator类创建TreeMap Now, I want to create one of that maps and assign it to one of my beans. 现在,我想创建其中一个映射并将其分配给我的一个bean。 I also know map values beforehand and I'm interested in leaving Spring inject them. 我也事先知道地图值,并且我有兴趣让Spring注入它们。 The question is, can a map type be declared, built with a constructor param (I need it to pass the Comparator class) and be value-injected using Spring? 问题是,可以声明地图类型,使用构造函数参数构建(我需要它通过Comparator类)并使用Spring进行值注入吗?

This kind of declaration works, but no value can be injected later: 这种声明有效,但是以后不能再注入任何值:

<bean id="antennaFilteringManagerMap" class="java.util.TreeMap">
    <constructor-arg ref="nameComparator" />
</bean>

<bean id="nameComparator" class="com.tadic.model.detector.Antenna.NameComparator" />

On the other hand, if I use Spring map utilities, there are some ways to specify map's class, but the constructor arg cannot be passed: 另一方面,如果我使用Spring映射实用程序, 则有一些方法可以指定映射的类,但是无法传递构造函数arg:

<bean class="org.springframework.beans.factory.config.MapFactoryBean">
    <property name="targetMapClass">
        <value>java.util.TreeMap</value>
    </property>
    <property name="sourceMap">
        <map>
            <entry key-ref="antenna1" value-ref="locationEventFilteringManager1" />
        </map>
    </property>
</bean>

OR 要么

<util:map map-class="java.util.TreeMap">
    <entry key-ref="antenna1" value-ref="locationEventFilteringManager1" />
</util:map>

That's a nice workaround. 这是一个不错的解决方法。 I defined a subclass which extends from TreeMap for my specific case. 我为我的特定情况定义了一个从TreeMap扩展的子类。 This class adds the Comparator I want to use by default in the constructor: 此类在构造函数中默认添加了我要使用的Comparator

public static class LocationEventFilteringManagerMap extends
        TreeMap<Antenna, LocationEventFilteringManager> {

    public LocationEventFilteringManagerMap() {
        super(new Antenna.NameComparator());
    }

}

After that, I only need to specify the map-class to the util-map tag: 之后,我只需要将映射类指定为util-map标记:

<property name="_LocationEventFilteringManagerMap">
    <util:map
        map-class="mypackage.MyBean.LocationEventFilteringManagerMap">
        <entry key-ref="antenna1" value-ref="locationEventFilteringManager1" />
    </util:map>
</property>

Forcing the new class to construct the Map in that way, I avoid the needing of the constructor-arg injection for the Map and I can easily populate it. 强制新类以这种方式构造Map ,避免了Map constructor-arg注入,并且可以轻松地填充它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM