Spring 作为bean动态添加新队列、绑定和交换

Spring 作为bean动态添加新队列、绑定和交换,spring,rabbitmq,spring-amqp,spring-bean,spring-rabbit,Spring,Rabbitmq,Spring Amqp,Spring Bean,Spring Rabbit,我目前正在从事一个rabbit amqp实现项目,并使用SpringRabbit以编程方式设置我的所有队列、绑定和交换。(spring-rabbit-1.3.4和spring框架版本3.2.0) 在我看来,javaconfiguration类或基于xml的配置中的声明都是相当静态的。我知道如何为队列exchange设置更具动态性的值(例如名称) 或者像这样装订: @Configuration public class serverConfiguration { private String

我目前正在从事一个rabbit amqp实现项目,并使用SpringRabbit以编程方式设置我的所有队列、绑定和交换。(spring-rabbit-1.3.4和spring框架版本3.2.0)

在我看来,javaconfiguration类或基于xml的配置中的声明都是相当静态的。我知道如何为队列exchange设置更具动态性的值(例如名称) 或者像这样装订:

@Configuration
public class serverConfiguration {
   private String queueName;
   ...
   @Bean
   public Queue buildQueue() {
    Queue queue = new Queue(this.queueName, false, false, true, getQueueArguments());
    buildRabbitAdmin().declareQueue(queue);
    return queue;
   }
   ...
}
但我想知道是否有可能创建一个未定义数量的Queue和 将它们注册为bean,就像工厂注册其所有实例一样

我不太熟悉Spring@Bean注释及其局限性,但我试过了

@Configuration
public class serverConfiguration {
   private String queueName;
   ...
   @Bean
   @Scope("prototype")
   public Queue buildQueue() {
    Queue queue = new Queue(this.queueName, false, false, true, getQueueArguments());
    buildRabbitAdmin().declareQueue(queue);
    return queue;
   }
   ...
}
为了查看队列的多个bean实例是否已注册,我调用:

Map<String, Queue> queueBeans = ((ListableBeanFactory) applicationContext).getBeansOfType(Queue.class);

是否可以在运行时将bean动态添加到SpringApplicationContext?

您可以将bean动态添加到上下文:

context.getBeanFactory().registerSingleton("foo", new Queue("foo"));
但是管理员不会自动声明它们;您必须调用
admin.initialize()
,以强制它在上下文中重新声明所有AMQP元素


您不会在
@Bean
s中执行这两项操作,而只执行普通运行时java代码。

这听起来像是一项JMX任务。谢谢,这对我帮助很大。@Gary在spring boot中使用
addQueues
怎么样。如果出现
spring boot
,请扩展您的答案并解释详细信息好吗?
addQueues
只将它们添加到容器中,不会导致它们在代理上声明;他们必须在这样的背景下。在启动应用程序中,您可以通过
@Autowired
调用应用程序上下文,或在
main
方法中使用
ConfigurableApplicationContext=SpringApplication.run(application.class,args)获取对应用程序上下文的引用
context.getBeanFactory().registerSingleton("foo", new Queue("foo"));