Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Annotations - Injecting Map of Objects

Tags:

java

spring

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);        
}
like image 273
Punter Vicky Avatar asked Mar 10 '23 23:03

Punter Vicky


1 Answers

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
like image 129
Sundararaj Govindasamy Avatar answered Mar 20 '23 20:03

Sundararaj Govindasamy