Tuesday, August 14, 2012

Collections: Wiring properties using props


Opera.java:
package com.lnn.collections;

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

public class Opera {
      private Properties instruments;

      public void setInstruments(Properties instruments) {
            this.instruments = instruments;
      }

      public void display() {
            for (Entry<Object, Object> 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="opera" class="com.lnn.collections.Opera">
            <property name="instruments">
                  <props>
                        <prop key="GUITAR">STRUM STRUM STRUM</prop>
                        <prop key="CYMBAL">CRASH CRASH CRASH</prop>
                        <prop key="HARMONICA">HUM HUM HUM</prop>
                  </props>
            </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("------------------Properties---------------------");
            Opera opera = context.getBean("opera", Opera.class);
            opera.display();
      }
}

No comments:

Post a Comment