how to get multiple instances of same bean in spring?
First you'll have to make MyService
a Spring bean. You can do this by annotating the class with @Component
. Next, as you say, Spring beans are Singletons by default, so this can be changed with one more annotation - @Scope("prototype")
.
A prototype bean scope means that each time you ask Spring for an instance of the bean, a new instance will be created. This applies to Autowiring, asking the application context for the bean with getBean()
, or using a bean factory.
Here is a simple example of how to register a desired number of beans of the same type
@Configurationpublic class MultiBeanConfig implements ApplicationContextAware { @Value("${bean.quantity}") private int quantity; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { for (int i = 0; i < quantity; i++) { ((ConfigurableApplicationContext)applicationContext).getBeanFactory() .registerSingleton("my-service-" + i, new MyService()); } assert(applicationContext.getBeansOfType(MyService.class).size() == quantity); } class MyService { }}