首页 > 解决方案 > 是否可以使用 Spring 注入 bean 列表

问题描述

我想从一个连接创建一个 JMS MessageProducer 列表。这些生产者中的每一个都需要从单独的会话中创建。

我想在春天做这样的事情,但显然这不起作用。

@Bean(destroyMethod = "close")
@Scope("prototype")
public Session jmsSession(final Connection jmsConnection) {
    <create a session>
}


@Bean(destroyMethod = "close")
public List<MessageProducer> jmsProvider(List<Session> jmsSessionList) {
    <Create a list of MessageProducers from the list of jmsSessionList>
}

有什么办法可以做到这一点?

  1. 从一个连接创建特定数量的会话。(会话数是 yml 文件中的配置属性)
  2. 将 Session 列表注入另一个 bean 以创建 MessageProducer
  3. 指定destroyMethod 来销毁它们。

标签: javaspring-jms

解决方案


你应该能够做你想做的事。

  1. 为此,您需要创建多个Sessionbean,如下所示:
    @Configuration
    class SessionsConfiguration {
    
      @Autowired
      private GenericApplicationContext applicationContext;
    
      @Value("${your.configuration.key}")
      private int sessionsCount;
    
      @PostConstruct
      fun init() {
        for (int i : sessionsCount) {
            applicationContext.registerBean() // Here you have multiple possibilities. 
            // Check reference documentation at https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/support/GenericApplicationContext.html
        }
      }
    }
    
  2. 您的代码应该已经这样做了。
  3. 您的代码应该已经这样做了。

推荐阅读