Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a Map<String, List> in java springs?

Tags:

java

spring

How to inject a Map in java spring framework? If possible please provide some sample code.

Is the following legal?

<property name="testMap">     <map>         <entry>             <key>                 <value>test</value>             </key>             <value>                 <list>                     <value>String</value>                     <value>String</value>                 </list>             </value>         </entry>     </map>  </property> 
like image 317
Aravind Avatar asked Mar 18 '11 05:03

Aravind


People also ask

How do you inject a Map from a Yaml file in spring boot?

How to Inject a Map from a YAML File. Spring Boot has taken data externalization to the next level by providing a handy annotation called @ConfigurationProperties. This annotation is introduced to easily inject external properties from configuration files directly into Java objects.

How do you inject spring values?

Method 3 : Using @Value annotation This method involves applying @Value annotation over bean properties whose values are to be injected. The string provided along with the annotation may either be the value of the bean field or it may refer to a property name from a properties file loaded earlier in Spring context.

Can we Autowire Map in spring?

No, you can't inject them into a Map where the key is the return value of a method call on a bean.


1 Answers

Define a Map like this first inside your applicationContext.xml:

<util:list id="list1">     <value>[email protected]</value>     <value>[email protected]</value> </util:list>  <util:list id="list2">     <value>[email protected]</value>     <value>[email protected]</value> </util:list>  <util:map id="emailMap" value-type="java.util.List">     <!-- Map between String key and List -->     <entry key="entry1" value-ref="list1" />     <entry key="entry2" value-ref="list2" />     ... </util:map> 

Then use this Map in any bean of yours like this:

<bean id="myBean" class="com.sample.beans">     <property name="emailMap" ref="emailMap" /> </bean> 
like image 175
anubhava Avatar answered Sep 29 '22 21:09

anubhava