Tuesday, August 14, 2012

Collections: Wiring Map with map(LinkedHashMap) property


Opera.java:
package com.lnn.collections;

import java.util.Map;
import java.util.Map.Entry;

public class Opera {
      private Map<String, String> instruments;

      public void setInstruments(Map<String, String> instruments) {
            this.instruments = instruments;
      }

      public void display() {
            for (Entry<String, String> entry : instruments.entrySet()) {
                  System.out.println(entry.getKey() + " --> " + entry.getValue());
            }
      }
}
collections.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      <bean id="operaMap" class="com.lnn.collections.Opera">
            <property name="instruments">
                  <map>
                        <entry key="Guitar-Key" value="Guitar-Value"/>
                        <entry key="Piano-Key" value="Piano-Value"/>
                        <entry key="Violin-Key" value="Violin-Value"/>                      
                  </map>
            </property>
      </bean>
</beans>
Test.java:
package com.lnn.collections;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
      public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("collections.xml");
            System.out.println("------------------Map---------------------");
            Opera operaMap = context.getBean("operaMap", Opera.class);
            operaMap.display();
      }
}

No comments:

Post a Comment