1
votes

I have a Spring (boot) application that's using spring-rabbit, and I create the binding beans as needed like so:

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QueueBindings {

    // first binding

    @Bean
    public Queue firstQueue(@Value("${rabbitmq.first.queue}") String queueName) {
        return new Queue(queueName);
    }

    @Bean
    public FanoutExchange firstExchange(@Value("${rabbitmq.first.exchange}") String exchangeName) {
        return new FanoutExchange(exchangeName);
    }

    @Bean
    public Binding firstBinding(Queue firstQueue, FanoutExchange firstExchange) {
        return BindingBuilder.bind(firstQueue).to(firstExchange);
    }

    // second binding

    @Bean
    public Queue secondQueue(@Value("${rabbitmq.second.queue}") String queueName) {
        return new Queue(queueName);
    }

    @Bean
    public FanoutExchange secondExchange(@Value("${rabbitmq.second.exchange}") String exchangeName) {
        return new FanoutExchange(exchangeName);
    }

    @Bean
    public Binding secondBinding(Queue secondQueue, FanoutExchange secondExchange) {
        return BindingBuilder.bind(secondQueue).to(secondExchange);
    }

}

The issue I have is that there are only two pieces of information per 3 beans, the queue name and the exchange name.

Is there a way to add an arbitrary number of beans to the context rather than copy and paste a bunch of @Bean methods? I'd want something like "for each name in this list, add these three beans with this connection."

1

1 Answers

0
votes

To register an arbitrary number of beans programatically, you need to drop down to a lower-level API. You can use @Import on a configuration class to reference an ImportBeanDefinitionRegistrar implementation. In the registerBeanDefinitions method of the registrar, you'd then register bean definitions for all of the beans.

If you want to be able to externally configure the beans that will be registered, an ImportBeanDefinitionRegistrar can be EnvironmentAware. This allows you to have the Environment injected so that you can use its properties to customise the beans that your registrar will register.