【问题标题】:how to get multiple instances of same bean in spring?如何在春天获得同一个bean的多个实例?
【发布时间】:2017-02-22 16:13:28
【问题描述】:

默认情况下,spring bean 是单例的。我想知道是否有办法让同一个 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);
                }

    }
}

这里是服务类

    public class MyService implements Runnable {

    private String name;

    public Myservice(int i){

    name=String.ValueOf(i);

    }
  }

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

谢谢

【问题讨论】:

  • 你可以在你的应用上下文中使用 bean factory 来实现
  • @bart.s:你能举个例子并说明怎么做吗?
  • 好的,看看下面的答案

标签: spring spring-boot spring-4 spring-bean


【解决方案1】:

首先,您必须将 MyService 设为 Spring bean。您可以通过使用 @Component 注释类来做到这一点。接下来,正如您所说,Spring bean 默认情况下是 Singletons,因此可以通过另外一个注释来更改它 - @Scope("prototype")

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

【讨论】:

  • 在 bean 上的较新配置而不是使用 @Scope("prototype)@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  • 那么我如何为每个实例化的名称命名。你能告诉我如何在上面的用例中使用它吗?
【解决方案2】:

这里是一个简单的例子,说明如何注册所需数量的相同类型的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 {

    }
}

【讨论】:

  • 你还在做新的MyService()。我希望服务成为组件
  • 为什么它对你如此重要?
  • 因为你做的和我上面做的没什么不同。
猜你喜欢
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 2019-06-12
  • 2020-05-26
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多