Wednesday, 13 September 2017

What is Autowiring and How to use it ?


AUTOWIRING : Avoids some of the Spring configuration.


EXAMPLE
Class definition
public class Point {
   private int x;
   private int y; 
   // getters n setters
}  
 

public class Triangle {
   private Point pointA;
   private Point pointB;
   private Point pointC;
   // getters n setters
 

   public void draw(){
     s.o.p.("Point1:"+ getPointA().getX() +","+ getPointA().getY());
           s.o.p.("Point2:"+ getPointB().getX() +","+ getPointB().getY());
           s.o.p.("Point3:"+ getPointC().getX() +","+ getPointC().getY());
   }

 }





XML WITHOUT AUTOWIRING (BIGGER CONFIG )
<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="pointA" ref="pointOne" />
      <property name="pointB" ref="pointTwo" />
      <property name="pointC" ref="pointThree" />
   </bean>
</beans>









XML WITH AUTOWIRING (SMALLER CONFIG )
Here names of class properties are matching with property names in XML, so just define autowire="byName" attribute and there is no need to define 3 property tags.
 
<beans> 
   <bean id="
pointA" class="com.shaan.exmaple.Point">
      <property name="x" value="0" />
      <property name="y" value="0" />
   </bean>
   <bean id="
pointB" class="com.shaan.exmaple.Point">
      <property name="x" value="-20" />
      <property name="y" value="0" />
   </bean>
   <bean id="
pointC" class="com.shaan.exmaple.Point">
      <property name="x" value="20" />
      <property name="y" value="0" />
   </bean>

 
   <bean id="triangle" class="com.shaan.exmaple.Triangle"

         autowire="byName">
   </bean>
</beans>






Similarly, autowire="byType" will match the class type of bean.
It is only applicable when there is only one property of that type in bean class.
(Not applicable in above example, because there are many Point objects needed in same bean)

autowire="constructor" will inject values at constructor running time, not by setters.
Works similarly as "byType" and used when there is only one property of that type in bean class.

Default autowiring is autowiring=off and wiring must be done manually.

No comments:

Post a Comment

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