我正在尝试调用RabbitTemplate#addBeforePublishPostProcessors
和RabbitTemplate#addAfterReceivePostProcessors
,而不会过多地干扰Spring的自动配置。
我正在尝试执行此操作,但是我的MessagePostProcessor
没有触发(我在正在发布的消息中没有看到“ test_header”)。
@EventListener
void test(ApplicationPreparedEvent event) {
ConfigurableApplicationContext applicationContext = event.getApplicationContext();
RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
rabbitTemplate.addBeforePublishPostProcessors(new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setHeader("test_header", "test_header_value");
return message;
}
});
}
为此合适的地方是什么?
我也尝试过听ApplicationStartedEvent
。
答案 0 :(得分:0)
使用BeanPostProcessor
。
@SpringBootApplication
public class So56155062Application {
public static void main(String[] args) {
SpringApplication.run(So56155062Application.class, args);
}
@Bean
public static BeanPostProcessor bpp() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RabbitTemplate) {
((RabbitTemplate) bean).setBeforePublishPostProcessors(m -> {
m.getMessageProperties().setHeader("foo", "baz");
return m;
});
}
return bean;
}
};
}
@Bean
public ApplicationRunner runner(RabbitTemplate template) {
return args -> template.convertAndSend("foo", "bar");
}
@RabbitListener(queues = "foo")
public void listen(String in, @Header("foo") String header) {
System.out.println(in + header);
}
}
请注意static
修饰符