How to get multiple instances of the same bean in spring?

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

Here is what i am doing now

    @Configuration
    public class ApplicationMain { 

     @Value("${service.num: not configured}")
    private int num;

    //more code

@PostConstruct
public void run(){

        for (int i = 0; i < num ; i++) {
                    MyService ser = new MyService(i);
                    Future<?> tasks = executor.submit(ser);
                }

    }
}

Here is a class of service

    public class MyService implements Runnable {

    private String name;

    public Myservice(int i){

    name=String.ValueOf(i);

    }
  }

I have simplified my business here. I want to have MyService as spring bean and get as much as possible based on configuartion (which is num) in the above for-loop? I wonder how this is possible.

thank

+4
source share
2 answers

MyService a Spring bean. , @Component. , , Spring beans , - @Scope("prototype").

bean , , Spring bean, . Autowiring, bean getBean() bean factory.

+8

, beans

@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 {

    }
}
0

Source: https://habr.com/ru/post/1670466/


All Articles