我有三豆:电影、导演、英雄
电影豆:
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 {
}
弹簧核心.xml
<bean id="movieBean" class="Movie" autowire="constructor" />
<bean id="directorBean" class="Director"></bean>
<bean id="heroBean" class="Hero"></bean>
请注意,在上面的 XML 中,我已经声明了所有三个 bean
主类
ApplicationContext context = new ClassPathXmlApplicationContext("spring-core.xml");
Movie movie = (Movie) context.getBean("movieBean");
System.out.println(movie);
输出是“ m1”,即调用的构造函数是Movie(Director director, Hero hero)
我的问题是:如果我们使用构造函数自动装配,为什么只调用这个构造函数以及IOC 容器在注入依赖项时如何在多个构造函数中进行选择