ti-enxame.com

Spring Framework: Preenchendo um Mapa <Enum, Object> com util: map

Eu tenho essa classe de fábrica, que eu quero conectar via mola para a configuração em tempo de execução do mapa. O mapa contém um objeto enum e um pojo padrão.

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;
    }
}

Estou tendo problemas com meu utilitário Spring: fiação do mapa, pois não sei como fazer referência correta a um tipo de enum específico ao definir o valor da chave. A referência do bean para o valor do mapa é fácil. Todos os exemplos de fiação de mapa de mola parecem assumir que a chave é uma string!

<!-- the value object bean -->
<bean id="cell" class="com.xx.xx.common.index.entity.CellEntity"/>

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

Editar

Então eu refatorei o mapeamento

<bean id="genericEntityFactory" class="com.xx.xx.common.index.GenericEntityFactoryImpl" >
    <property name="indexEntityMap">
        <map >
            <entry key="com.xx.xx.common.index.CELL"><ref bean="cell"/></entry>
        </map>   
    </property>
</bean>

mas a suposição de que a primavera será inteligente falha ...

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'genericEntityFactory' defined in class path resource [com/xx/xx/common/index/index-application-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [Java.util.LinkedHashMap] to required type [Java.util.Map] for property 'indexEntityMap'; nested exception is Java.lang.IllegalArgumentException: Cannot convert value of type [Java.lang.String] to required type [com.xx.xx.common.index.IndexType] for property 'indexEntityMap[com.xx.xx.common.index.CELL]': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:480)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.Java:409)
    at Java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.Java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:221)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:164)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.Java:429)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.Java:729)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.Java:381)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.Java:84)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.Java:42)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.Java:173)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.Java:197)
    ... 17 more
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type [Java.util.LinkedHashMap] to required type [Java.util.Map] for property 'indexEntityMap'; nested exception is Java.lang.IllegalArgumentException: Cannot convert value of type [Java.lang.String] to required type [com.xx.xx.common.index.IndexType] for property 'indexEntityMap[com.xx.xx.common.index.CELL]': no matching editors or conversion strategy found
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.Java:391)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.Java:1288)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.Java:1249)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1010)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:472)
    ... 32 more
Caused by: Java.lang.IllegalArgumentException: Cannot convert value of type [Java.lang.String] to required type [com.xx.xx.common.index.IndexType] for property 'indexEntityMap[com.xx.xx.common.index.CELL]': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.Java:219)
    at org.springframework.beans.TypeConverterDelegate.convertToTypedMap(TypeConverterDelegate.Java:508)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.Java:194)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.Java:138)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.Java:386)
    ... 36 more
14
emeraldjava

Encontrei uma solução alternativa ao definir cada enum que pretendo adicionar ao mapa como um bean separado - graças a criando-spring-bean-from-Java-5-enum

<bean id="CELL" class="com.xx.xx.common.index.IndexType" factory-method="valueOf">
    <constructor-arg>
        <value>CELL</value>
    </constructor-arg>
</bean>

<bean id="APN" class="com.xx.xx.common.index.IndexType" factory-method="valueOf">
    <constructor-arg>
        <value>APN</value>
    </constructor-arg>
</bean>

Tendo definido as enumerações, posso refizá-las com chave no mapa

<bean id="genericEntityFactory" class="com.xx.xx.common.index.GenericEntityFactoryImpl" >
    <property name="indexEntityMap">
        <map>
            <entry key-ref="CELL"><ref bean="cell"/></entry>
            <entry key-ref="APN"><ref bean="apn"/></entry>
        </map>   
    </property>
</bean>
12
emeraldjava

Aqui está um formato alternativo e mais curto:

<bean id="versionService" class="my.service.VersionService" 
        p:animalDAOMap-ref="animalDAOMap"/>

<util:map id="p:animalDAOMap">
    <entry key="chicken" value-ref="chickenDAO"/>
    <entry key="monkey" value-ref="monkeyDAO"/>
    <entry key="pig" value-ref="pigDAO"/>
</util:map>

Certifique-se de incluir o espaço para nome

xmlns:util="http://www.springframework.org/schema/util"

E o esquema

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

A propósito, eu estou usando o Spring 3.0+ aqui

10
chris

Tem o mesmo erro que você. Consegui evitá-lo movendo minha enumeração para um arquivo independente e tornando-a pública.

Então meu

public enum EventType { INFO, ERROR }

São colocados em

EventType.Java

Também tenho apenas um pacote, se isso importa de alguma forma. Estou injetando dependência dessa maneira (através do xml pelo construtor arg):

spring.xml:

<constructor-arg>
    <map>
        <entry key="INFO" value-ref="consoleEventLogger"></entry>
        <entry key="ERROR" value-ref="combinedEventLogger"></entry>
    </map>
</constructor-arg>

Isso está funcionando para mim com o Spring-core 4.3.6

Eu acredito que há uma explicação, que depende da reflexão e da lógica interna da Spring. Mas não tenho muita experiência Java e não posso fornecer isso.

0
Mosolov Sergey