Sobes.tech
Junior — Middle

How to select and implement two separate Bean instances of the same type in a Spring application?

sobes.tech AI

Answer from AI

In Spring, you can create two separate instances of a Bean of the same type, assign them different names (identifiers), and inject them by name using the @Qualifier annotation.

Example:

@Component("beanOne")
public class MyBean {
    // implementation
}

@Component("beanTwo")
public class MyBean {
    // different implementation or configuration
}

// Injection
@Autowired
@Qualifier("beanOne")
private MyBean firstBean;

@Autowired
@Qualifier("beanTwo")
private MyBean secondBean;

If using configuration via @Bean:

@Configuration
public class AppConfig {
    @Bean("beanOne")
    public MyBean myBeanOne() {
        return new MyBean();
    }

    @Bean("beanTwo")
    public MyBean myBeanTwo() {
        return new MyBean();
    }
}

Thus, you can manage different instances of the same type and inject the needed one based on the context.