Dynamically add new queues, bindings and exchanges as beans

I am currently working on a rabbit-amqp implementation project and am using spring -rabbit to programmatically configure all my queues, bindings and exchanges. (spring -rabbit-1.3.4 and spring-framework version 3.2.0)

The declaration in the javaconfiguration or xml configuration class is, in my opinion, pretty static. I know how to set a more dynamic value (e.g. name) for a queue, exchange or bind as follows:

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

But I was wondering if it is possible to instantiate an undefined Queue instance and register them as beans as a factory, registering all its instances.

I am not very familiar with Spring @Bean annotation and its limitations, but I tried

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

And to check if multiple instances of the beans queue are registered, I call:

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

But this will only result in mapping 1:

 name of the method := the last created instance. 

Is it possible to dynamically add beans at runtime in a SpringApplicationContext?

+10
spring spring-amqp spring-bean spring-rabbit rabbitmq
source share
1 answer

Dynamically add beans to the context:

 context.getBeanFactory().registerSingleton("foo", new Queue("foo")); 

but they will not be announced automatically by the administrator; you will have to call admin.initialize() to force it to re-declare all AMQP elements in context.

You would not do any of these in @Bean s, just normal Java code.

+7
source share

All Articles