Punter Vicky Punter Vicky - 1 month ago 14
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>
</map>
</property>
</bean>


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 ;
@Autowired
private GetDefaultImpl getDefaultImpl;
@Autowired
private GetPersonImpl getPersonImpl;
@Autowired
private GetCompanyImpl getCompanyImpl;

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


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

Answer

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

You can do like this...

@Configuration
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.

propertyname={key1:'value1',key2:'value2',....}

In your code,

@Value("#{${propertyname}}")  
private Map<String,String> propertyname;

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

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