コンストラクターによるオートワイヤリングのSpring docは、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 があります。
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を使用しています