Punter Vicky Punter Vicky - 4 months ago 46
Java Question

Spring Annotations - Injecting Map of Objects

Using XML annotation , I am injecting a map using the below config -

<bean id = "customerfactory" class = "com.brightstar.CustomerFactory">
<property name = "getCustomerMap">
<map key-type = "java.lang.String" value-type = "com.brightstar.CustomerImpl">
<entry key = "DEFAULT" value-ref = "getDefaultImpl"></entry>
<entry key = "PERSON" value-ref = "getPersonImpl"></entry>
<entry key = "COMPANY" value-ref = "getCompanyImpl"></entry>

I have created 3 beans - DefaultImpl , PersonImpl and CompanyImpl. How can I inject these as a map using Spring Annotation?

EDIT: For now , I have performed the below but not sure if it is the recommended approach

private Map<String, CustomerImpl> getCustomerMap ;
private GetDefaultImpl getDefaultImpl;
private GetPersonImpl getPersonImpl;
private GetCompanyImpl getCompanyImpl;

private static final String DEFAULT = "DEFAULT";
private static final String COM = "PERSON";
private static final String SOM = "COMPANY";

public void init(){
getCustomerMap = new LinkedHashMap<String,CustomerImpl>();
getCustomerMap.put(DEFAULT, getDefaultImpl);
getCustomerMap.put(PERSON, getPersonImpl);
getCustomerMap.put(COMPANY, getCompanyImpl);


1.Inject a Map which contains Objects, (Using Java Config)

You can do like this...

public class MyConfiguration {
    @Autowired private WhiteColourHandler whiteColourHandler;

    @Bean public Map<ColourEnum, ColourHandler> colourHandlers() {
        Map<ColourEnum, ColourHandler> map = new EnumMap<>();
        map.put(WHITE, whiteColourHandler);
        //put more objects into this map here
        return map;


2.Inject a Map which contains Strings (Using properties file)

You can inject String values into a Map from the properties file using the @Value annotation and SpEL like this.

For example, below property in the properties file.


In your code,

private Map<String,String> propertyname;

Note: 1.The hashtag as part of the annotation.

    2.Values must be quotes, else you will get SpelEvaluationException