构造函数的自动装配Spring文档说它与byType相同,但是对于构造函数参数。
如果是这样,那么为什么以下程序不会失败:
config.xml中
<bean id="traingle" class="org.practise.autowiring.Triangle" autowire="constructor" />
<bean id="pointA" class="org.practise.autowiring.Point">
<property name="x" value="0"/>
<property name="y" value="10"/>
</bean>
<bean id="pointB" class="org.practise.autowiring.Point">
<property name="x" value="220"/>
<property name="y" value="330"/>
</bean>
<bean id="pointC" class="org.practise.autowiring.Point">
<property name="x" value="40"/>
<property name="y" value="60"/>
</bean>
在上面的例子中,我有3个相同类型的bean(Point),我试图在下面的类中注入:
public class Triangle {
private Point pointA;
private Point pointB;
private Point pointC;
public Triangle(Point pointA, Point pointB, Point pointC) {
this.pointA = pointA;
this.pointB = pointB;
this.pointC = 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());
}
}
点
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;
}
}
执行代码:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("org/practise/autowiring/spring-autowiring.xml");
Triangle triangle = (Triangle) context.getBean(Triangle.class);
triangle.draw();
}
传递并打印以下内容:
Aug 18, 2013 2:04:56 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@43ee1619: startup date [Sun Aug 18 14:04:56 PDT 2013]; root of context hierarchy
Aug 18, 2013 2:04:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [org/practise/autowiring/spring-autowiring.xml]
Aug 18, 2013 2:04:56 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@13c6395b: defining beans [traingle,pointA,pointB,pointC]; root of factory hierarchy
Point A: 0, 10
Point B: 220, 330
Point C: 40, 60
当我将接线类型更改为“byType”时,它会抛出预期的异常。只有在上述情况下它才能正常工作。我正在使用Spring 3.2