Sobes.tech
Junior — Middle

Can you give an example of a scenario where it is necessary to use multiple instances of a Bean component in Spring?

sobes.tech AI

Answer from AI

Multiple instances of a Bean component in Spring are used when you need different configurations or states for the same class. For example:

  • Different connection settings to multiple databases (each Bean with different parameters).
  • Several implementations of an interface, selected based on context.
  • Different instances with unique parameters for handling various tasks.

Example:

@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource1() {
        // Configuration for the first database
    }

    @Bean
    public DataSource dataSource2() {
        // Configuration for the second database
    }
}

Here are two Beans of the same type DataSource with different settings.

Can you give an example of a scenario where it is… - sobes.tech