top of page

@Qualifier Annotation

In Spring, the @Qualifier annotation is used to resolve the ambiguity when multiple beans of the same type are present in the application context. It is used alongside the @Autowired annotation to specify which bean should be injected when there are multiple candidates.


Defining Multiple Beans of the Same Type:

@Configuration
public class AppConfig {

    @Bean
    public Service myService1() {
        return new ServiceImpl1();
    }

    @Bean
    public Service myService2() {
        return new ServiceImpl2();
    }
}

Using @Qualifier to Resolve Ambiguity:

@Component
public class MyComponent {

    private final Service service;

    @Autowired
    public MyComponent(@Qualifier("myService1") Service service) {
        this.service = service;
    }

    public void doSomething() {
        service.perform();
    }
}

In this example:

  • AppConfig class defines two beans of type Service, named myService1 and myService2.

  • MyComponent class has a dependency on Service. Using @Autowired along with @Qualifier("myService1"), it specifies that myService1 should be injected.


Without the @Qualifier, Spring would not know which Service bean to inject, leading to a NoUniqueBeanDefinitionException.


Important Points:

  1. Field Injection: You can also use @Qualifier for field injection:

@Autowired
@Qualifier("myService1")
private Service service;

2 . Setter Injection:

@Autowired
public void setService(@Qualifier("myService1") Service service) {
    this.service = service;
}

Recent Posts

See All
@SpringBootApplication annotation

The @SpringBootApplication annotation is a crucial part of any Spring Boot application. It is a convenience annotation that combines...

 
 
 

留言


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page