@Qualifier Annotation
- Manbodh ratre
- Jul 11, 2024
- 1 min read
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:
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;
}
留言