Spring - How do you set Enum keys in a Map with annotations

hashmap with enum as key
groovy enum map
spring util:map
java enum map to function
java treemap enum key
java map enum to string
mapping between two enums java
java enum to map

I've an Enum class

public enum MyEnum{
    ABC;
}

than my 'Mick' class has this property

private Map<MyEnum, OtherObj> myMap;

I've this spring xml configuration.

<util:map id="myMap">
    <entry key="ABC" value-ref="myObj" />
</util:map>

<bean id="mick" class="com.x.Mick">
    <property name="myMap" ref="myMap" />
</bean>

and this is fine. I'd like to replace this xml configuration with Spring annotations. Do you have any idea on how to autowire the map?

The problem here is that if I switch from xml config to the @Autowired annotation (on the myMap attribute of the Mick class) Spring is throwing this exception

nested exception is org.springframework.beans.FatalBeanException: Key type [class com.MyEnum] of map [java.util.Map] must be assignable to [java.lang.String]

Spring is no more able to recognize the string ABC as a MyEnum.ABC object. Any idea?

Thanks

This worked for me...

My Spring application context:

<util:map id="myMap">
  <entry key="#{T(com.acme.MyEnum).ELEM1}" value="value1" />
  <entry key="#{T(com.acme.MyEnum).ELEM2}" value="value2" />
</util:map>

My class where the Map gets injected:

public class MyClass {

    private @Resource Map<MyEnum, String> myMap;
}

The important things to note are that in the Spring context I used SpEL (Spring Expression Language) which is only available since version 3.0. And in my class I used @Resource, neither @Inject (it didn't work for me) nor @Autowired (I didn't try this). The only difference I'm aware of between @Resource and @Autowired, is that the former auto-inject by bean name while the later does it by bean type.

Enjoy!

Spring - How do you set Enum keys in a Map with annotations, I've an Enum class public enum MyEnum{ ABC; }. than my 'Mick' class has this property private Map<MyEnum, OtherObj> myMap;. I've this spring xml  I've an Enum class public enum MyEnum{ ABC; } than my 'Mick' class has this property private Map<MyEnum, OtherObj> myMap; I've this spring xml configuration.

Mapping Enum Keys With EnumMaps [Snippets], I've an Enum class public enum MyEnum{ ABC; } than my 'Mick' class has this property private Map myMap; I've this spring xml configuration. EnumMap is a specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

Application context

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd ">

<bean id="myProvider" class="com.project.MapProvider">
    <property name="myMap" ref="myMap"/>
</bean>

<util:map id="myMap" key-type="com.project.MyEnum" value-type="com.project.ValueObject">
    <entry>
        <key><value type="com.project.MyEnum">FOO</value></key>
        <ref bean="objectValue1"/>
    </entry>
</util:map>
</beans>

Java class

package com.project;

public class MapProvider {

    private Map<MyEnum, ValueObject> myMap;

    public void setMyMap(Map<MyEnum, ValueObject> myMap) {
        this.myMap = myMap;
    }
}

Java: Create a Map With Predefined Keys, An often forgotten part of the JDK, learn how and why you should consider in handy when we want to define maps with enum types as keys: An EnumMap is a specialized Map . We'll create a map for a given enum: spring.profiles.active=​prod Frequently Used Annotations in Spring Boot Applications. As explained earlier, Hibernate maps the enum values to an int or a String. But PostgreSQL expects you to set the value as an Object. If you want to map your enum to PostgreSQL’s enum type, you need to implement a custom mapping. But don’t worry, if you extend Hibernate’s EnumType, you just need to override 1 method to set the value as an

Should be:

public class Mick {

  private Map<MyEnum, OtherObj> myMap;

  @Autowired
  public void setMyMap(Map<MyEnum, OtherObj> myMap) {
    this.myMap = myMap;
  }
}

Have a look at http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config

Updated

The problem is that according to the util schema, you cannot specify the key or value types. You can however to implement a MapFactoryBean of your own (just inherit from org.springframework.beans.factory.config.MapFactoryBean). One ceveat - notice that the generic definition (even thought erased in runtime) doesn't get in the way.

Spring Util Map Annotation with Enum key, We can use the Builder annotation of Lombok to get a cleaner syntax. In this option, we would use an enum to predefine the keys. Then, you'll configure a Spring Boot API app that allows you to register your favorite beers  Do you mean setting up the enum itself? I don't think that's possible. You cannot instantiate enums because they have a static nature. So I think that Spring IoC can't create enums as well. On the other hand, if you need to set initialize something with a enum please check out the Spring IoC chapter. (search for enum) There's a simple example

The <util:map> element has key-type, resp. value-type attributes, that represents the class of the keys, resp. the values. If you specify the fully qualified class of your enum in the key-type attribute, the keys are then parsed into that enum when creating the map.

Spring verifies during injection that the map's key and value types -as declared in the class containing the map- are assignment-compatible with the key and value types of the map bean. This is actually where you get the exception from.

Configuration Metadata - Project Metadata API Guide, I wanted create java.util.Map in spring context xml file which injects the Map to one of my service class, but i was struggling with this because my Map's key is an enum value, Finally I was able fix that issue as following,  l'élément <util:map> a un type de clé, resp. attribut value-type, qui représente la classe des clés, resp. valeur. Si vous spécifiez la classe entièrement qualifiée de votre enum dans l'attribut key-type, les clés sont alors analysées dans cet enum lors de la création de la carte.

Beginning Spring, Generating Your Own Metadata by Using the Annotation Processor "value": "​create", "description": "Create the schema and destroy previous data. If your property is of type Map , you can provide hints for both the keys and the values We recommend that you use an Enum for those two values instead. Instead, it makes more sense to compare with the actual values of an enum. However, because of the limitations of annotations, such an annotation cannot be made generic. This is because arguments for annotations can only be concrete values of a specific enum, not instances of the enum parent class.

How and when to use Enums and Annotations, you. learned. in. thiS. chaPter representing the primary key attribute of the persistent class Annotations used to map 1:1,1:M, Annotations used to map Date, Time, Timestamp, Enum, and byte[] Java types to corresponding is used to perform persistence operations Spring's FactoryBean implementations to create an  In JPA, Enum types must be marked with the @Enumerated annotation, which can take an EnumType defining if the Java Enumeration is mapped to either a String or an Integer column type. Mapping Enum to a String column type. To map the Enum to a String database column type, you need to specify the EnumType.STRING value when using the @Enumerated

JPA and Enums via @Enumerated, This course is designed to help you make the most effective use of Enums could be treated as a special type of classes and annotations as The EnumSet​< T > is the regular set optimized to store enums is very close to the regular map with the difference that its keys could Spring Interview Questions. This article walks you through the lean ways of creating a Map with a fixed (predefined) set of keys.. Option One: Using Lombok and Jackson. In this approach, we would create a simple class.

Comments
  • It's not clear what you're trying to do. What sort of annotations are you thinking of?
  • I'd like to use the @Autowired annotation but it's not working. Do I have to specify something else to tell Spring to treat that Key value as an Enum instead of a String?
  • Remember to use '$' instead of '.' for separating an inner enum from an outer class in Spring EL.
  • Just a follow up that @Autowired will also yield Key type [class com.foo.Bar$BAZ] of map [java.util.Map] must be assignable to [java.lang.String], @Resource is the winner. +1 @Amir, $ is a gotcha.
  • Question said "I'd like to replace this xml configuration with Spring annotations." yet there's still config XML here. Does that mean you can't do this in Spring purely with annotations?
  • @Jonik I think the replacement intended was the bean and resource injection part, not the map part. Otherwise, I'm not sure why this answer was selected.
  • Thank you very much for this. Only @ Resource works. I tried @ Autowired and it did not work. Strange, but I'll just go with @ Resource
  • The answer needs a bit more explanation of what you listed here.
  • I've created map with enum as key and used it for setter argument. I thought it is obvious :)
  • Hi David, I know about the @Autowired annotation. Here the problem is that if I autowire the map Spring is no more able to recognize the string ABC as a MyEnum.ABC object. With XML configuration it works fine, with annotations configuration it's throwing this Exception nested exception is org.springframework.beans.FatalBeanException: Key type [class com.MyEnum] of map [java.util.Map] must be assignable to [java.lang.String]