Tuesday, August 14, 2012

Collections: Wiring List with list(allow duplicates) and set(no duplicates)


Opera.java:
package com.lnn.collections;

import java.util.List;

public class Opera {
      private List<String> instruments;

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

      public void display() {
            for (String instrument : instruments) {
                  System.out.println(instrument);
            }
      }
}
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="operaList" class="com.lnn.collections.Opera">
            <property name="instruments">
                  <list>
                        <value>Guitar</value>
                        <value>Piano</value>
                        <value>Piano</value>
                        <value>Violin</value>
                        <value>Violin</value>
                  </list>
            </property>
      </bean>
      <bean id="operaSet" class="com.lnn.collections.Opera">
            <property name="instruments">
                  <set>
                        <value>Guitar</value>
                        <value>Piano</value>
                        <value>Piano</value>
                        <value>Violin</value>
                        <value>Violin</value>
                  </set>
            </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("------------------List---------------------");
            Opera operaList = context.getBean("operaList", Opera.class);
            operaList.display();
            System.out.println("------------------Set----------------------");
            Opera operaSet = context.getBean("operaSet", Opera.class);
            operaSet.display();
      }
}

No comments:

Post a Comment