@Qualifier annotation in spring


@Qualifier

This annotation is used along with the @Autowired annotation. When you need more control of the dependency injection process, @Qualifier it can be used. @Qualifier can be specified on individual constructor arguments or method parameters. This annotation is used to avoid the confusion that occurs when you create more than one bean of the same type and want to wire only one of them with a property.

 

 

Autowire Need for Disambiguation

The @Autowired annotation is a great way of making the need to inject a dependency in Spring explicit. And although it's useful, there are use cases for which this annotation alone isn't enough for Spring to understand which bean to inject.

By default, Spring resolves autowired entries by type.

If more than one bean of the same type is available in the container, the framework will throw NoUniqueBeanDefinitionException, indicating that more than one bean is available for autowiring.

Let's imagine a situation in which two possible candidates exist for Spring to inject as bean collaborators in a given instance:

 

@Component("fooFormatter")
public class FooFormatter implements Formatter {  

    public String format() {

        return "foo";

    }

}


@Component("barFormatter")
public class BarFormatter implements Formatter {  

    public String format() {

        return "bar";

    }

}

@Component
public class FooService {      

    @Autowired
    private Formatter formatter;

}


If we try to load FooService into our context, the Spring framework will throw a NoUniqueBeanDefinitionException. This is because Spring doesn't know which bean to inject. To avoid this problem, there are several solutions. The @Qualifier annotation is one of them

@Qualifier Annotation

By using the @Qualifier annotation, we can eliminate the issue of which bean needs to be injected.

Let's revisit our previous example and see how we solve the problem by including the @Qualifier annotation to indicate which bean we want to use:

 

public class FooService {      

    @Autowired

    @Qualifier("fooFormatter")

    private Formatter formatter;

}


.

Related Articles

post a comment