What is autowiring in Spring?

Connecting beans together in the Spring container is called autowiring. It is the process by which collaborating beans are tied together without the developer having to write explicit object instantiation code.

It reduces the code as well as the development time because it removes the need to write dependency injection code.

What are the different modes of autowiring in Spring?

When using XML configuration the autowiring mode can be specified using the autowire attribute in the <bean> tag. The modes of bean autowiring are:

  1. no: the default autowiring mode is no autowiring in which case the developer has to provide explicit bean reference using the ref attribute.
  2. byName: the bean is injected by matching the property, that needs to be autowired, with a bean that has the same name. The property name must match a bean name for this type of autowiring to work.
  3. byType: the bean is injected by matching the property, that needs to be autowired, with a bean of the same type. If no matches are found, the property is not set. If more than one matches are found an error occurs.
  4. constructor: the dependency is injected by calling the constructor with a bean whose type matches with the constructor argument. If no matches are found, an error occurs.

How does autowiring internally work?

Spring calls the setter method for the property when autowiring mode is byName and byType.

When autowiring mode is constructor and the class defines multiple constructors, then Spring will call the constructor with the most number of parameters.

What is autowiring by the constructor?

Autowiring by constructor is similar to autowiring by type. It is applied to a constructor argument. Consider the example of a Vehicle class which has a dependency on the Engine class. The following code injects the dependency explicitly without using autowiring:

Get hands-on with 1400+ tech skills courses.