Constructor type Autowiring in Spring Framework

Posted By : Gursahib Singh | 25-Aug-2019

What is Wiring:
The process of injecting dependencies of the bean is known as wiring.
It can be done in two ways:
1. Explicit Wiring
2. Implicit Wiring or Auto Wiring 
Types of  Implicit Wiring(autowire) attribute:
1. byName
2. byType
3. constructor
Introduction of constructor autowiring:
When the autowire attribute value is constructor then spring container checks whether any bean instance is running in the container whose Data Type is same as bean property( variable ) Data Type or not.
Depending on the availability of the bean instances, Spring container identifies the matching constructor and invokes that constructor to inject the bean dependencies.
In this you may get three cases:
 When no bean is found with the matching data type then bean property will not be injected.
 When only one bean is found with the matching data type and without matching constructor then bean property will not be injected.
 When only one bean is found with the matching data type and with matching constructor then it will be injected.
 If there are two or more beans are found with the matching data type then-
 The Container will try to pick one bean from available multiple beans based on byName autowire process first. 
2. When one bean is not selected based on byName autowire process then ignores multiple beans found with the given type. 

Example  Constructor type Autowirng process:

 1. Create a java project and inject all  Spring core related jar files in Build Path.
 2. Create a package in src for all the following java files.

class Developer

package com.mkyong.common;

public class Developer {
	private Language language;

	//autowire by constructor
	public Developer(Language language) {
		this.language = language;
	}

	//...

}

class Language

package com.mkyong.common;

public class Language {
	private String name;
	//...
}

Spring.xml file

  <bean id="developer" class="com.mkyong.common.Developer"> 
		<constructor-arg>
			<ref bean="language" />
		</constructor-arg>
  </bean>
		
  <bean id="language" class="com.mkyong.common.Language" >
		<property name="name" value="Java" />
  </bean>

If autowire by constructor is enabled, than the constructor type property will no longer be needed to be set manually.Spring container will itself inject it after finding its compatible type.

This is how Autwire by Constructor type can be done in Spring framework

 

About Author

Author Image
Gursahib Singh

Gursahib is a software developer having key skills in J2SE and J2EE. His hobbies are playing chess, reading and learning new softwares.

Request for Proposal

Name is required

Comment is required

Sending message..