Spring Autowiring by Constructor

In Spring framework, autowiring by constructor is similar to byType, but applies to constructor arguments. In autowire enabled bean, it look for class type of constructor arguments, and then do a autowire by type on all constructor arguments.

Please note that if there isn’t exactly one bean of the constructor argument type in the container, a fatal error is raised.

Example of Autowiring by Constructor

How to enable constructor autowiring

Autowiring by constructor is enabled by using autowire="constructor" in bean definition in configuration file (i.e. application-context.xml).

Your example is doing too much, obfuscating the lesson. I came to learn about auto wiring the constructor. Why isn’t full name part of the constructor injection? Whats the point of adding full name to the example? This is just clutter and it detracts from the lesson. Same with department bean name. Another non constructor wiring – what point does it add to the example?

Despite all this unnecessary clutter, you skimp the meat of the meal. The lesson doesn’t provide much detail about the EmployeeBean constructor injection. Somehow springs just magically figures out to pass the DepartmentBean instance to the EmployeeBean constructor. I would be interested in what is going on here behind the scenes. This is the nut of the lesson – not Spring setter injections.

Thanks for the feedback. I appreciate you time. 1) “Why isn’t full name part of the constructor injection?” – Why it should be? It’s way to show that you can have setter as well as constructor injection – “both” – in same bean definition. 2) “Same with department bean” – It is present in example because it has to be injected into other bean. There is absolutely no necessity to do constructor autowiring to make sense out of this example. 3) “lesson doesn’t provide much detail about the EmployeeBean constructor injection” – I have clearly written that Autowiring by constructor is enabled by using autowire="constructor" in bean definition in configuration file [ In section Autowire dependency using constructor ]. And that’s how it is done in most cases.

And read 3rd para of post for more clarity. Now I am making it bold.

But thanks again for asking the questions, it means information may confuse others as well – so I have added info box with additional information to save other’s time.