title: Spring Dependency Injection Example
body: <p>i am working on Spring dependency Injection.</p>
  
  <p>I want to calculate area of a rectangle and circle using spring and make use of dependency injection.</p>
  
  <p>Till now i have completed this:</p>
  
  <p><strong>Interface:</strong></p>
  
  <pre><code>public interface Shape {
     double calculateArea();
  }
  </code></pre>
  
  <p><strong>Circle class</strong></p>
  
  <pre><code>public class Circle implements Shape{
  
      @Autowired
      public double radius;
  
      @Override
      public double calculateArea() {
          double area = (Math.PI)*radius*radius;
          return area;
      }
  
  }
  </code></pre>
  
  <p><strong>Rectangle class:</strong></p>
  
  <pre><code>public class Rectangle implements Shape {
  
      @Autowired
      public double length;
  
      @Autowired
      public double breadth;
  
      @Override
      public double calculateArea() {
          double area = length*breadth;
          return area;
      }
  }
  </code></pre>
  
  <p><strong>bean xml:</strong></p>
  
  <pre><code>&lt;bean id="circle" class="org.package.test.Circle"&gt;
      &lt;property name="radius" value="12"/&gt;
  &lt;/bean&gt;
  &lt;bean id="rectangle" class="org.package.test.Rectangle"&gt;
      &lt;property name="length" value="12"/&gt;
      &lt;property name="breadth" value="10"/&gt;
  &lt;/bean&gt;
  
  &lt;bean id="geometricalShape" class="org.package.test.GeometricalShape"&gt;
      &lt;constructor-arg ref="circle"/&gt;
      &lt;constructor-arg ref="rectangle"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p><strong>GeometricalShape.java</strong></p>
  
  <pre><code>private Shape shape;
  
  private Shape shape1;
     /**
      * Inject circle object via Constructor
      */
     public GeometricalShape(Shape shape,Shape shape1) {
        this.shape = shape;
        this.shape1 = shape1;
     }
  
     public void calculate() {
        shape.calculateArea();
        shape1.calculateArea();
     }
  }
  </code></pre>
  
  <p><strong>Main.Java</strong></p>
  
  <pre><code>public class Main {
      public static void main(String[] args) {
          @SuppressWarnings("resource")
          ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
  
          GeometricalShape bean1=context.getBean("geometricalShape", GeometricalShape.class);
          geometryBean1.calculate();           
      }
  }
  </code></pre>
  
  <p>Here i am directly providing the radius/length or breadth as a static value. How can i provide it as a dynamic value (That is any value i want by changing it in Spring?) Is there any better way of doing this using Spring dependency Injection? Any suggestions please?</p>