Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

how to get multiple instances of same bean in spring?

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

    @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 the Service class

    public class MyService implements Runnable {

    private String name;

    public Myservice(int i){

    name=String.ValueOf(i);

    }
  }

I have simplified my usecase here. I want to have MyService as spring bean and get as many as possible based on configuartion (which is num) in the above for-loop? wondering how that is possible.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...