Friday, October 2, 2015

Spring Framework- 7 - Alias and idref tags

The <alias> tag is used to add an additional name to an existing bean, as show in the code below:

public class DrawingApp {

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

while the <alias> tag is defined as below:

<bean id="triangle" class="com.project.springDemo.Triangle">
<property name="pointA">
<bean class="com.project.springDemo.Point">
<property name="x" value="10"/>
<property name="y" value="100"/>
</bean>
</property>
<property name="pointB" ref="Bean-pointB"/>
<property name="pointC" ref="Bean-pointC"/>
</bean>
<alias name="triangle" alias="threeSided"/>

</beans>

Note: the <alias> tag can be entirely replaced with the name attribute on the <bean> tag as below, However, this is not recommended.

<bean id="triangle" class="com.project.springDemo.Triangle" name="threeSided">

---------------------------------------------------------------------------------------------------

The idref attribute is used to handle exception when a referred bean isn't present in the respective xml

Usage is as below:

<beans>
<bean id="triangle" class="com.project.springDemo.Triangle">
<property name="pointA">
<bean class="com.project.springDemo.Point">
<property name="x" value="10"/>
<property name="y" value="100"/>
</bean>
</property>
<property name="pointB">
                    <idref="Bean-pointB"/>
  </property>
<property name="pointC" ref="Bean-pointC"/>
</bean>

<bean id="Bean-pointB" class="com.project.springDemo.Point">
<property name="x" value="20"/>
<property name="y" value="200"/>
</bean>
<bean id="Bean-pointC" class="com.project.springDemo.Point">
<property name="x" value="30"/>
<property name="y" value="300"/>
</bean>

<alias name="triangle" alias="threeSided"/>
</beans>

No comments:

Post a Comment