【发布时间】:2015-12-03 20:26:43
【问题描述】:
首先我需要告诉我知道如何使用 Spring 配置文件中的类型和索引来解决这个问题。但我想了解当存在歧义构造函数时,spring 如何选择构造函数。
Pojo 类
package a.b.c;
public class Square {
private String color;
private int sideLength;
public Square(String color, int sideLength) {
System.out.println("Constructor id #1");
this.sideLength = sideLength;
this.color = color;
}
public Square(int sideLength, String color) {
System.out.println("Constructor id #2");
this.sideLength = sideLength;
this.color = color;
}
public Square(Integer sideLength, String color) {
System.out.println("Constructor id #3");
this.sideLength = sideLength;
this.color = color;
}
public void draw() {
System.out.println("square color : " + color + ", sideLenth : " + sideLength);
}
}
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="square" class="a.b.c.Square">
<constructor-arg type="java.lang.String" value="red" />
<constructor-arg type="int" value="10" />
</bean>
</beans>
调用类
package a.b.c;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Square square = (Square) context.getBean("square");
square.draw();
}
}
通过这种安排,它选择 #2 构造函数。
如果交换构造函数在源文件中的位置如下,则无需任何配置更改
package a.b.c;
public class Square {
private String color;
private int sideLength;
public Square(int sideLength, String color) {
System.out.println("Constructor id #2");
this.sideLength = sideLength;
this.color = color;
}
public Square(String color, int sideLength) {
System.out.println("Constructor id #1");
this.sideLength = sideLength;
this.color = color;
}
public Square(Integer sideLength, String color) {
System.out.println("Constructor id #3");
this.sideLength = sideLength;
this.color = color;
}
public void draw() {
System.out.println("square color : " + color + ", sideLenth : " + sideLength);
}
}
除了方法位置没有任何变化。 现在它选择 #1 构造函数。
我的问题是当出现歧义时选择构造函数的逻辑是什么。
注意:我知道这可以使用 index.html 解决。
【问题讨论】:
-
你通过documentation了吗?
-
@Sotirios Delimanolis 感谢您提供此链接。是的,在发布之前,我确实浏览了这些以及大量的博客和技术文章。所有这些都说如何解决这个问题。但没有人说它是如何选择的。我的意思是选择构造函数在源中更改时如何更改。
-
你的意思是当它交换源文件中的方法时执行构造函数得到改变?
-
是的。它总是选择中间的 3 个
-
谁能指出我在 github 中的源文件。所以我能理解..
标签: spring