Tuesday, 12 September 2017

How to use collections as properties of Spring beans ?


INTSTED OF value / ref attributes :

<property name="X" value="Y" />
OR
<property name="X" ref="Y" />

USE tags list, set or map  with sub-tags ref or value :
<property name="X">
  <list>
     <value>1</value>
     <value>2</value>
     ...   </list>
</property>

OR
 
<property name="X">
  <list>
     <ref bean="Y1" />
     <ref bean="Y2" />
     ...
   </list>
</property>



EXAMPLE 1
Change previous example by having List of points instead of different point objects.

Class definition

public class Point {
  private int x;
  private int y;
  // getters n setters


public class Triangle {
  private List<Point> points;

  // getters n setters

  public void draw(){

    for (Point point : points) {
       s.o.p.("Point:"+ point.getX() +","+ point.getY());

    }
  }

}

XML
<beans>
  <bean name="triangle" class="com.shaan.exmaple.Triangle">
    <property name="points">

       <list>
         <ref bean="pointOne" />
         <ref bean="pointTwo" />
         <ref bean="pointThree" />
       </list>
    </property>
  </bean>
 

  <bean id="pointOne" class="com.shaan.exmaple.Point">
    <property name="x" value="0" />
    <property name="y" value="0" />
  </bean>
  <bean id="pointTwo" class="com.shaan.exmaple.Point">
    <property name="x" value="-20" />
    <property name="y" value="0" />
  </bean>
  <bean id="pointThree" class="com.shaan.exmaple.Point">
    <property name="x" value="20" />
    <property name="y" value="0" />
   </bean>
 

</beans>





* Type conversion : Spring will auto-convert the type depending on data type of collection elements in class. 

USAGE
BeanFactory factory = new XmlBeanFactory(new
FileSystemResource("spring.xml"));
Triangle t = (Triangle) factory.getBean("triange");
t.draw();




EXAMPLE 2
USING value SUB-TAGS WITH LIST OF INT VALUES
<bean ...>
  <property name="val">
    <list>
      <value>500</value>
      <value>120</value>
      <value>62</value>
    </list>   </property>
</bean>

Class
public class Triangle {
  private List<Integer> val;

  // getters n setters

No comments:

Post a Comment

Note: only a member of this blog may post a comment.