InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
Multiple Beans of Same Type
- In a configuration class, can you define multiple beans with the same return type (e.g., Employee)?
- If yes, how would you differentiate and use them?
Yes, you can define multiple beans of the same type (e.g., Employee) in a configuration class. To differentiate and use them, you assign each bean a unique name using the @Bean annotation or @Qualifier.
Example:
@Bean(name = "manager")
public Employee manager() {
return new Employee("Manager");
}
@Bean(name = "developer")
public Employee developer() {
return new Employee("Developer");
}
How to use them:
Inject the specific bean using @Qualifier:
@Autowired
@Qualifier("manager")
private Employee managerEmployee;
@Autowired
@Qualifier("developer")
private Employee developerEmployee;
Summary:
1: You can have multiple beans of the same type.
2: Use unique names and @Qualifier to select the one you need. This makes it easy to manage and use different beans of the same class in your application.