consider the following simple example
package com.yagapp.auto;
public class PointA {
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;
}
}
package com.yagapp.auto;
public class PointA {
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;
}
}
--------------------------------------------------
package com.yagapp.auto;
import org.springframework.beans.factory.annotation.Autowired;
public class Circle {
private PointA point;
public PointA getPoint() {
return point;
}
@Autowired
public void setPoint(PointA point) {
this.point = point;
}
public void draw()
{
System.out.println("Circle drwan");
}
}
--------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:context="http://www.springframework.org/schema/context">
<bean id="Circle" class="com.yagapp.auto.Circle"/>
<bean id="point1" class="com.yagapp.auto.PointA">
<property name="x" value="2"/>
<property name="y" value="3"/>
</bean>
</beans>
------------------------------------------------
package com.yagapp.auto;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCircle {
/**
* @param args
*/
public static void main(String[] args) {
AbstractApplicationContext factory = new ClassPathXmlApplicationContext("Circle_Spring.xml");
Circle c = factory.getBean("Circle",Circle.class);
c.draw();
}
}
if execute this TestCircle class , first spring will try to inject the Point object into Circle
how it will inject ?
here it will work with its default behavior
auto wire by TYPE
means ?
spring first checks the configuration xml , for the bean which has the class value as com.yagapp.auto.PointA (and make sure we have only one such bean defined in the xml)
then it will create the bean and inject that bean into circle class
thats it we have a circle object with PointA object
this is the way how @Autowired will work with its default behavior , auto wire by type
No comments:
Post a Comment