Junior — Middle
Is it possible to have multiple Bean objects in the Spring context at the same time?
sobes.tech AI
Answer from AI
Yes, in the context of Spring, it is possible to have multiple Bean objects simultaneously. The Spring container manages many Beans, each of which can be unique by type or name. If necessary, you can create multiple instances of the same class with different Bean names or use annotations such as @Qualifier to distinguish them during injection.
Example of creating two Beans of the same type with different names:
@Configuration
public class AppConfig {
@Bean
public Service serviceOne() {
return new ServiceImpl1();
}
@Bean
public Service serviceTwo() {
return new ServiceImpl2();
}
}
// Injection with specific Bean reference
@Autowired
@Qualifier("serviceOne")
private Service service;