如何在spring中获得同一bean的多个实例?

如何在spring中获得同一bean的多个实例?,spring,spring-boot,spring-4,spring-bean,Spring,Spring Boot,Spring 4,Spring Bean,默认情况下,SpringBean是单例的。我想知道是否有一种方法可以获取同一bean的多个实例进行处理 以下是我目前的工作 @Configuration public class ApplicationMain { @Value("${service.num: not configured}") private int num; //more code @PostConstruct public void run(){ for

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

以下是我目前的工作

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

    }
}
我在这里简化了我的用例。 我想让MyService成为Springbean,并在上面的for循环中基于配置(即
num
)获得尽可能多的服务?想知道这怎么可能


谢谢

首先,您必须使
MyService
成为Springbean。可以通过使用
@Component
注释类来完成此操作。接下来,正如您所说,SpringBean在默认情况下是单例的,所以这可以通过一个注释来改变-
@Scope(“prototype”)


一个原型bean范围意味着每次您向Spring请求bean实例时,都会创建一个新实例。这适用于自动连接,使用
getBean()
请求应用程序上下文以获取bean,或者使用bean工厂。

下面是一个简单的示例,说明如何注册所需数量的相同类型的bean

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

    }
}
@配置
公共类MultiBeanConfig实现ApplicationContextAware{
@值(${bean.quantity}”)
私人整数数量;
@凌驾
public void setApplicationContext(ApplicationContext ApplicationContext)抛出BeansException{
对于(int i=0;i
您可以从应用程序中使用bean factory来实现这一点context@bart.s:您能给出一个示例并演示如何执行吗?当然,请看下面的答案:在bean上使用较新的配置,而不是使用
@Scope(“prototype”)
@Scope(scopeName=ConfigurableBeanFactory.Scope\u prototype)
我如何为每个实例化的服务命名。您能告诉我如何在上面的用例中使用它吗?您仍在使用新的
MyService()
。我希望服务成为组件为什么它对您如此重要?因为您所做的与我上面所做的没有什么不同。
@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 {

    }
}