user93796
user93796

Reputation: 18379

initializating map in spring

I am reading a map from some config using spring expression.Now how can i construct a bean out of it.

<bean id="xyz"  class= "java.util.Map" >
   <!-- how to pass $xyz to this -->
    <!-- i know how to pass static entries to  it  using entry tag , but how abut map? !-->
</bean>

How can i pass my map to bean xyz?

For String following code can be used.

<bean id="x" class ="java.util.String >
  <construtor-arg>  $x
   </constructort-arg>
</bean>

But for map there is not constuctor that takes map as inp

Upvotes: 2

Views: 159

Answers (1)

Ralph
Ralph

Reputation: 120811

Use the Spring util schema

<?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.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util.xsd">


  <bean id="yourBean" class="yourBean">
    <property name="aPrameterOfTypeMapInYourBean">
      <map>
        <entry key="first" value="hallo"/>
        <entry key="second" value="world"/>
        <entry key="third" value="that is easy"/>
        <entry key="forth" value="and hopefully solve your problem"/>

        <entry key="yourParam" value="$x"/>

      </map>
    </property>
  </bean>

</beans>

Spring also support merging of collections (<map> should have a merge attribute). Therefore you need to define two maps, and specify the one of them as parent of the other one.

More Details:

Upvotes: 4

Related Questions