Share on Google+Share on Google+

Spring Map Property

Advertisement
In this tutorial you will learn about the spring map property.

Spring Map Property

The Spring Framework has bean support for the Collections. It provide list, set, map and props elements. Here in this tutorial you will see about the map elements which is used to set values inside the map.

CollegeBean.java

package collection.map.example;

import java.util.Map;

public class CollegeBean {
  private Map<Object, Object> maps;

  public Map<Object, Object> getMaps() {
    return maps;
  }

  public void setMaps(Map<Object, Object> maps) {
    this.maps = maps;
  }

  @Override
  public String toString() {
    return "College [Maps=" + maps + "]";
  }
}

StudentBean.java

package collection.set.example;

public class StudentBean {
  private String name;
  private String address;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  @Override
  public String toString() {
    return "Student [address=" + address + ", name=" + name + "]";
  }
}

MapMain.java

package collection.map.example;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MapMain {
   public static void mainString[] args )
      {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext("context.xml");
      CollegeBean coll = (CollegeBean)beanfactory.getBean("collegeBean2");
      System.out.println(coll);
      }
}

context.xml

<!-- Spring Map Property -->
    <bean id="collegeBean2" class="collection.map.example.CollegeBean">
    <property name="maps">
    <map>
      <entry key="Key 1" value="1" />
      <entry key="Key 2" value-ref="studentBean2" />
      <entry key="Key 3">
        <bean class="collection.map.example.StudentBean">
          <property name="name" value="mkyongMap" />
          <property name="address" value="address" />
        
        </bean>
      </entry>
    </map>
  </property>

  </bean>

  <bean id="studentBean2" class="collection.map.example.StudentBean">
    <property name="name" value="mkyong1" />
    <property name="address" value="address 1" />
  </bean>
<!-- End -->

When you run this application it will display output as shown below:


College [Maps={Key 1=1, Key 2=Student [address=pune, name=suraj], Key 3=Student [address=patna, name=satya]}]

Download this example code

Advertisements

Advertisement

Posted on: August 13, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.