It is used to reduce some of configuration. By default
“autowiring” is off you need to call it explicitly.
Autowiring can be in three ways 1. byName, 2. byType and 3. Constructor.
byName: autowiring can be done using bean names. If bean
names and members variables of class are same then you can autowire using
byName you do not need to define ref in bean.
byType: autowiring
can be done using bean type, but the condition is it will done for single bean
– autowiring can be done with single wiring.
constructor: autowiring can be done using class constructor,
condition is it applies for single class not multiple classes.
DrawingApp.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 Point pointA;
private Point pointB;
private Point pointC;
public Point
getPointA() {
return pointA;
}
public void setPointA(Point
pointA) {
this.pointA = pointA;
}
public Point
getPointB() {
return pointB;
}
public void setPointB(Point
pointB) {
this.pointB = pointB;
}
public Point
getPointC() {
return pointC;
}
public void setPointC(Point
pointC) {
this.pointC = pointC;
}
public void draw(){
System.out.println("Point A
= (" + getPointA().getX()+", "+getPointA().getY()+")");
System.out.println("Point B
= (" + getPointB().getX()+", "+getPointB().getY()+")");
System.out.println("Point C
= (" + getPointC().getX()+", "+getPointC().getY()+")");
}
}
Point.java
package org.yash.watertechsol;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
spring.xml
<?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="triangle"
class="org.yash.watertechsol.Triangle"
autowire="byName">
</bean>
<bean id
="pointA"
class="org.yash.watertechsol.Point">
<property name="x"
value="0" />
<property name="y"
value="0" />
</bean>
<bean id
="pointB"
class="org.yash.watertechsol.Point">
<property name="x"
value="-20" />
<property name="y"
value="0" />
</bean>
<bean id
="pointC"
class="org.yash.watertechsol.Point">
<property name="x"
value="0" />
<property name="y"
value="20" />
</bean>
</beans>
No comments:
Post a Comment