如何在春季获得同一个bean的多个实例

如何在春季获得同一个bean的多个实例

本文介绍了如何在春季获得同一个bean的多个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,spring bean是单例的.我想知道是否有一种方法可以获取同一bean的多个实例进行处理.

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

这是我目前正在做的

    @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);
                }

    }
}

这是服务类

    public class MyService implements Runnable {

    private String name;

    public Myservice(int i){

    name=String.ValueOf(i);

    }
  }

我在这里简化了用例.我想将MyService作为spring bean,并在上述for循环中基于configuartion(num)获取尽可能多的内容?想知道这怎么可能.

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.

谢谢

推荐答案

首先,您必须将MyService制成Spring bean.您可以通过使用@Component注释类来实现.接下来,正如您所说,Spring bean默认情况下为Singletons,因此可以通过添加另一个注释-@Scope("prototype")进行更改.

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").

原型bean范围意味着每次您向Spring请求该bean的实例时,都会创建一个新实例.这适用于自动装配,使用getBean()或使用bean工厂向应用程序上下文询问bean.

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.

这篇关于如何在春季获得同一个bean的多个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:58