how to get multiple instances of same bean in spring?

后端 未结 2 1919
夕颜
夕颜 2020-12-20 13:27

By default, spring beans are singletons. I am wondering if there is a way to get multiple instances of same bean for processing.

Here is what I do currently

2条回答
  •  生来不讨喜
    2020-12-20 13:36

    Here is a simple example of how to register a desired number of beans of the same type

    @Configuration
    public 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 {
    
        }
    }
    

提交回复
热议问题