Muhammad Hewedy
Muhammad Hewedy

Reputation: 30078

Configure MessagePostProcessor globally in Spring RabbitTemplate

Related to How do we hook into before/After message processing using @RabbitListener

If I want to configure RabbitTemplate globally and set MessagePostProcessor, what is the best way?

  1. Should I copy the bean definition from RabbitAutoConfiguration?
  2. Or should I intercept the bean definition using BeanPostProcessor?

The problem with first solution is that, RabbitTemplate in RabbitAutoConfiguration is not just bounding the properties to the bean instance but also set message converts:

MessageConverter messageConverter = this.messageConverter.getIfUnique();
if (messageConverter != null) {
    template.setMessageConverter(messageConverter);
}

So, should I duplicate this logic as follows, or just follow the second option of BeanPostProcessor as in Sleuth?

@ConfigurationProperties(prefix = "spring.rabbitmq.template")
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory,
                                     ObjectProvider<MessageConverter> messageConverterObjectProvider) {

    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    MessageConverter messageConverter = messageConverterObjectProvider.getIfUnique();
    if (messageConverter != null) {
        template.setMessageConverter(messageConverter);
    }
    template.setBeforePublishPostProcessors(myBeforePublishMPP());
    return template;
}

Upvotes: 2

Views: 2419

Answers (2)

Gary Russell
Gary Russell

Reputation: 174769

I would do it the first way so the application.properties are applied, but change the method signature to receive the ObjectProvider< MessageConverter> like they do in Sleuth.

Upvotes: 1

Artem Bilan
Artem Bilan

Reputation: 121550

I would say there is just enough to @Autowired an auto-configured RabbitTemplate and inject your MessagePostProcessor into that RabbitTemplate:

@Autowired
private RabbitTemplate rabbitTemplate;

@PostConstruct
public void init() {
    this.rabbitTemplate.setBeforePublishPostProcessors(myMessagePostProcessor());
}

@Bean
public MessagePostProcessor myMessagePostProcessor() {
    return message -> null;
}

Upvotes: 2

Related Questions