Spring automatically define the how to wire beans together by setting autowire property on each bean. it remove lot of Xml code writing overheads.
Here we understand this feature with example-Directory Structure-
class Ract.java
package com.test;
public class Ract {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Triangle.javapublic class Ract {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.test;
public class Triangle {
private String type;
private int height;
private Ract ract;
public Ract getRact() {
return ract;
}
public void setRact(Ract ract) {
this.ract = ract;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void draw()
{
System.out.println( getType()+"Triangle.\n The height is="+getHeight() );
System.out.println("ractangle is="+ract.getName());
}
}
class DrawApp.javapublic class Triangle {
private String type;
private int height;
private Ract ract;
public Ract getRact() {
return ract;
}
public void setRact(Ract ract) {
this.ract = ract;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void draw()
{
System.out.println( getType()+"Triangle.\n The height is="+getHeight() );
System.out.println("ractangle is="+ract.getName());
}
}
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawApp {
public static void main(String a[])
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Triangle tri= (Triangle) context.getBean("triangle");
tri.draw();
}
}
Xml file spring.xml import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawApp {
public static void main(String a[])
{
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Triangle tri= (Triangle) context.getBean("triangle");
tri.draw();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="ract" class="com.test.Ract">
<property name="name" value="abcd"></property>
</bean>
<bean id="triangle" class="com.test.Triangle" autowire="byName">
<property name="type" value="Equilateral"></property>
<property name="height" value="2"></property>
</bean>
</beans>
Output is-
EquilateralTriangle.
The height is=2
ractangle is=abcd
The height is=2
ractangle is=abcd
For Further Reading,
0 comments:
Post a Comment