in Spring

Spring ambiguity problem

Introduction

Spring ambiguity problem is a common misconfiguration problem it occurs when you have more then one bean that qualifies for wiring, in this case spring can not solve the problem and throws exception

org.springframework.beans.factory.NoUniqueBeanDefinitionException

In this tutorial I will show you what couses this problem and how to address it.

To demonstrate the problem I will use one interface Knight and two implementations DevelopmentKnight and ProductionKnight. Here is the code

Java Configuration [NoUniqueBeanDefinitionException]

To wire the beans I will use java configuration.

Here I have used name property to name the beans accordingly , in case name property is not used names of the beans would be:

  • getKnight
  • getKnightProd

spring will name the beans using the method name that creates it. Since this would not be fun :), I have added especial names.

Note: This configuration will throw exception NoUniqueBeanDefinitionException, reason is clearly visible in the MainConfig class above I have created two methods annotated with @Bean that returns same interface. This will confuse spring as it will not be able to decide what method should be used to create Knight bean.

 

Unit Test

To see how problem occurs I will use this test class

If you run this test class exception will be thrown and test will fail.

@Qualifier annotation

To solve the problem of ambiguity lets first use @Qualifier annotation to instruct spring what implementation we really want. Here is the modified test class

If you run this example all will be green !

@Primary annotation

Another way of dealing with ambiguity is to instruct spring how to solve the problem when it occurs by marking one bean as primary, this is where @Primary annotation comes in. Observe modified configuration.

As you can see I have added @Primary annotation and now spring knows how to solve the ambiguity problem.

@Primary annotation can be mixed with @Qualifier, lets say that in some especial case we want to autowire ProductionKnight, here is how to do this

 

Spring is awesome!

Write a Comment

Comment