This week one of my students in my Spring Core course ran into an issue how Spring was performing dependency inject. By default, the Spring Framework will perform dependency injection by type. This generally works fine, since you often will only have one bean in the Spring context for a given type. But this is not always the case.
When you do have more than one bean of a given type, you need to tell Spring which bean you wish it to use for dependency injection. If you fail to do so, Spring will throw a NoUniqueBeanDefinitionException exception, which means there’s more than one bean which would fulfill the requirement.
There are two simple ways you can resolve the NoUniqueBeanDefinitionException exception in Spring. You can use the
@Primary annotation, which will tell Spring when all other things are equal to select the primary bean over other instances of that type for the autowire requirement.
The second way, is to use the
@Qualifier annotation. Through the use of this annotation, you can give Spring hints about the name of the bean you want to use. By default, the reference name of the bean is typically the lower case class name.
In the video below, I go through the dependency injection example used in my Spring Core course, and show you how to modify it to get the
NoUniqueBeanDefinitionException. I then walk through first using the
@Primary annotation to give a preference to one bean over the other, and the I use the
@Qualifier to specifically select which instance of the bean into my classes.
While the Spring Framework does perform dependency injection by type by default, it does offer you a great deal of control how beans are autowired.