Java Spring框架:填充地图<;枚举,对象>;使用util:map

Java Spring框架:填充地图<;枚举,对象>;使用util:map,java,spring,Java,Spring,我有一个工厂类,我想通过spring连接它,以进行映射的运行时配置。映射包含一个枚举对象和标准pojo public class GenericEntityFactoryImpl implements GenericEntityFactory { private Map<IndexType,IEntity> indexEntityMap = null; @Override public IEntity getIndexEntity(IndexType ind

我有一个工厂类,我想通过spring连接它,以进行映射的运行时配置。映射包含一个枚举对象和标准pojo

public class GenericEntityFactoryImpl implements GenericEntityFactory
{
    private Map<IndexType,IEntity> indexEntityMap = null;

    @Override
    public IEntity getIndexEntity(IndexType index) {
        return indexEntityMap.get(index);
    }

    public Map<IndexType, IEntity> getIndexEntityMap() {
        return indexEntityMap;
    }

    public void setIndexEntityMap(Map<IndexType, IEntity> indexEntityMap) {
        this.indexEntityMap = indexEntityMap;
    }
}

我想这就是你需要的。注意,我认为不需要指定键类型和值类型属性。Spring应该能够解决这个问题

<bean id="genericEntityFactory" class="com.xx.xx.common.index.GenericEntityFactoryImpl">
  <property name="indexEntityMap" ref="indexEntityMapBean"/>
</bean>

<util:map id="indexEntityMapBean" 
       map-class="java.util.HashMap" 
       key-type="com.xx.xx.common.index.IndexType" 
       value-type="com.xx.xx.common.index.GenericEntityFactoryImpl">
           <entry key="com.xx.xx.common.index.IndexType.CELL">
                <ref bean="cell"/>
           </entry>
</util:map>


使用
的唯一原因是,我找到了一个解决方法,将计划添加到映射中的每个枚举定义为一个单独的bean,这要感谢


细胞
接入点
定义了枚举之后,我可以在映射中对它们进行键引用


以下是另一种较短的格式:


确保包含名称空间

xmlns:util="http://www.springframework.org/schema/util"
以及模式

http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util-3.0.xsd

顺便说一下,我在这里使用Spring 3.0+时,得到了与您相同的错误。我可以通过将我的枚举移动到独立文件并公开我的枚举来避免它

所以我的

放置在

EventType.java

如果这有什么关系的话,我只有一个包裹。 我以这种方式注入依赖项(通过构造函数arg的xml):

spring.xml:


这对我的spring core 4.3.6起到了作用

我相信有一种解释,这取决于反射和内部弹簧逻辑。但是我没有太多的Java经验,我无法提供这些经验。

(-1)这不起作用。Spring无法理解如何将密钥转换为枚举。在我的例子中,我得到:创建名为“la”的bean时出错:转换bean属性“sourceMap”的类型化字符串值时出错;嵌套异常为org.springframework.beans.ConversionNotSupportedException:未能将类型为“java.lang.String”的值转换为所需类型“com.t.layouthHolder$LA”;嵌套异常为java.lang.IllegalStateException:无法将[java.lang.String]类型的值转换为所需类型[com.t.LayoutHolder$LA]:未找到匹配的编辑器或转换策略
http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util-3.0.xsd
public enum EventType { INFO, ERROR }
<constructor-arg>
    <map>
        <entry key="INFO" value-ref="consoleEventLogger"></entry>
        <entry key="ERROR" value-ref="combinedEventLogger"></entry>
    </map>
</constructor-arg>