5
votes

TL;DR How to create Spring Boot AMQP connection factory programatically?

Hey,

In order to connect to my RabbitMQ I added these to my application.properties file of my Spring Boot app:

spring.rabbitmq.host=host
spring.rabbitmq.port=5672
spring.rabbitmq.username=myapp
spring.rabbitmq.password=mypass

And according to my understanding, these values are then used to create Spring Boot's auto configured ConnectionFactory, which I then use in:

@Bean
@Conditional(RabbitCondition.class)
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter completedOrderListenerAdapter) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(completedOrderQueueName);
    container.setMessageListener(completedOrderListenerAdapter);
    return container;
}

I would like to be able to use rabbitMQ credentials from different environment files which are not application.properties, so I would like to create ConnectionFactory bean programatically. How do I achieve this?

Thanks.

1

1 Answers

13
votes
@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setAddresses(address);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    return connectionFactory;
}