Java, Software Development, Spring

Spring Primary On Beans of a Class

We may not need the Spring Primary annotation on Beans of the same class, primarily when we use the @Bean annotation. When we have Java classes that implement the same interface, we will surely get the NoUniqueBeanDefinitionException exception. It happens when we annotate both classes with Component (or its derivatives) or create objects via the @Bean annotation. However, when we create two objects of the same type using @Bean, Spring may never throw the Exception, and we don’t need the Primary annotation.

We can try it! If you’re trying this out, you can review this post first to have a local working project.

NoUniqueBeanDefinitionException Example With Primary and Bean 

For the first part, we have a Java interface and two classes that implement it. We use the Component annotation (or its derivatives)  or create objects using the Bean annotation within a configuration file. 

We will get the following error when we run our codes with this configuration.

To resolve this issue, we need to annotate one of the Beans using the Spring Primary annotation. For instance, we annotate the following method with the Primary annotation.

No NoUniqueBeanDefinitionException Spring Configuration With Beans of the same Class

The following code snippet does not throw the exception. It works; therefore, we don’t need to use the Spring Primary annotation with the Bean annotation for the objects of the same class.

Why does this work? When we run the codes, we get the following chunk of the output.

Why not “In Dao Second”? There is a simple explanation for that. But it can be tricky if we are unfamiliar with Spring’s basics.

When Spring generates an instance of classes, it provides them with bean names (or IDs). In this case, wherein we use the Bean annotation, Spring uses the method names from which it creates the objects. Hence, we have two objects of the same class with the names “dao” and anotherDao”.  Then, the method that makes the Service object has a parameter named “dao.” As a result, Spring injects the bean with “dao” name.

When we change the last method’s parameter’s name, as shown in the following, we will get the NoUniqueBeanDefinitionException exception.

For more information, please consult the Spring documentation.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like