我有三个豆子:电影,导演,英雄
电影豆:
public class Movie {
private Director director;
private String name;
private Hero hero;
public Movie(Director director, Hero hero) {
System.out.println("m1");
this.director = director;
this.name = name;
this.hero = hero;
}
public Movie(Director director, String name) {
System.out.println("m2");
this.director = director;
this.name = name;
}
public Movie(Director director) {
System.out.println("m3");
this.director = director;
}
public Movie() {
System.out.println("m4");
}
}
导演和英雄豆:
public class Director {
}
public class Hero {
}
弹簧core.xml
<bean id="movieBean" class="Movie" autowire="constructor" />
<bean id="directorBean" class="Director"></bean>
<bean id="heroBean" class="Hero"></bean>
请注意在上面的XML中我已经声明了所有三个bean
MainClass
ApplicationContext context = new ClassPathXmlApplicationContext("spring-core.xml");
Movie movie = (Movie) context.getBean("movieBean");
System.out.println(movie);
输出是&#34; m1&#34; ,即调用的构造函数为Movie(Director director, Hero hero)
我的问题是:为什么只有这个构造函数被调用,如何 IOC容器会在注入依赖项时在多个构造函数中选择,如果我们使用构造函数使用自动装配
答案 0 :(得分:2)
只能调用一个构造函数来实例化bean。这与创建新Object时的方式类似,只调用一个构造函数(如果你想要非常精确,是的,你可以链接构造函数调用它)
在这种情况下,将使用具有大多数参数的构造函数,该构造函数可以由上下文中可用的其他bean满足。