Monday, July 22, 2013

06-Using-Constructor-Injection

Drawing.java
package org.yash.watertechsol;

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


public class DrawingApp {
      public static void main(String[] args){
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            Triangle triangle = (Triangle)context.getBean("triangle");
            triangle.draw();
      }
}


Triangle.java
package org.yash.watertechsol;

public class Triangle {
     
      private String type;
      private int height;
     
      public Triangle(String type){
            this.type=type;
      }

      public Triangle(String type, int height){
            this.type=type;
            this.height=height;
      }

      public Triangle(int height){
            this.height=height;
      }
     
      public int getHeight() {
            return height;
      }

      public void draw(){
            System.out.println(getType() + " Trianble drawn of height " + getHeight());
      }

      /*comment this this setter because we are not setting any property in xml*/
      /*
      public void setType(String type) {
            this.type = type;
      }
      */
      public String getType() {
            return type;
      }
}

spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
      <!-- It is blue print to object -->
      <bean id="triangle" class="org.yash.watertechsol.Triangle">
            <!-- constructor do not have name attribute -->
            <!--
            <constructor-arg value="Equilateral"></constructor-arg>
             -->
             <!--
            <constructor-arg type="int" value="20"></constructor-arg>
             -->
             <!--
            <constructor-arg type="java.lang.String" value="20">
</constructor-arg>
             -->
            <constructor-arg index="0" value="Equilateral"></constructor-arg>
            <constructor-arg index="1" value="20"></constructor-arg>
             
      </bean>

</beans>

No comments:

Post a Comment