Saturday, 2 September 2017

How to reference beans or use Object injection using Spring configuration ?


USE ref attribute of property tag. 
<property name="xyz" ref="bean2">

EXAMPLE
Class definition
public class Point {
   private int x;
   private int y; 
   // getters n setters
}  
public class Triangle {
   private Point point1;
   private Point point2;
   private Point point3;
   // getters n setters
   public void draw(){
     s.o.p.("Point1:"+ getPoint1().getX() +","+ getPoint1().getY());
            s.o.p.("Point2:"+ getPoint2().getX() +","+ getPoint2().getY());
            s.o.p.("Point3:"+ getPoint3().getX() +","+ getPoint3().getY());
   } }

XML
<beans> 
   <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>
   <bean id="triangle" class="com.shaan.exmaple.Triangle">
      <property name="point1" ref="pointOne" />
      <property name="point2" ref="pointTwo" />
      <property name="point3" ref="pointThree" />
   </bean>
</beans>


USAGE
BeanFactory factory = new XmlBeanFactory(new   
FileSystemResource("spring.xml"));

Triangle t = (Triangle) factory.getBean("triange");
t.draw();

No comments:

Post a Comment

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