1

I have three beans: Movie, Director, Hero

Movie bean:

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");
    }
}

Director and Hero beans:

public class Director {

}

public class Hero {

}

spring-core.xml

<bean id="movieBean" class="Movie" autowire="constructor" />

<bean id="directorBean" class="Director"></bean>
<bean id="heroBean" class="Hero"></bean>

Please note in the above XML I have declared all the three beans

MainClass

ApplicationContext context = new ClassPathXmlApplicationContext("spring-core.xml");

Movie movie = (Movie) context.getBean("movieBean");
System.out.println(movie);

The output is "m1" i.e. the constructor called is Movie(Director director, Hero hero)

My question is: why only this constructor is called and how IOC container will choose among multiple constructor while injecting dependencies if we are using autowiring using constructor

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Vishrant
  • 15,456
  • 11
  • 71
  • 120
  • 1
    http://stackoverflow.com/questions/21906361/dependency-injection-with-autowire-constructor-when-multiple-constructors-are – Gangadhar Jul 27 '16 at 14:53

1 Answers1

2

Only one constructor can be called to instantiate the bean. This is similar to how when creating a new Object you only invoke one constructor (If you want to be really precise, yes you could chain constructors calling this)

In this case the constructor with most arguments that can be satisfied by other beans available in the context will be used.

Vishrant
  • 15,456
  • 11
  • 71
  • 120
UserF40
  • 3,533
  • 2
  • 23
  • 34
  • Gangadhar linked to the exact thread which I was asking for: http://stackoverflow.com/questions/21906361/dependency-injection-with-autowire-constructor-when-multiple-constructors-are – Vishrant Jul 27 '16 at 15:08