Spring doc for Autowiring by constructor 说它与 byType 相同,但用于构造函数参数。
如果是这样,那么为什么以下程序不会失败:
配置文件
<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 个相同类型(Point)的 bean:
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