Autowiring and Misc Questions
Learn about a few interview questions regarding autowiring in Spring.
We'll cover the following
- What is autowiring in Spring?
- What are the different modes of autowiring in Spring?
- How does autowiring internally work?
- What is autowiring by the constructor?
- What are the limitations of autowiring?
- Is it possible to exclude a bean from being autowired?
- What does the @Autowired annotation do?
- What happens if we specify an interface instead of a class in getBean() method?
- Why do we need a no-arg constructor?
- What is Spring Security?
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:
no
: the default autowiring mode is no autowiring in which case the developer has to provide explicit bean reference using theref
attribute.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.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.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:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.