ConfigurationProperties

时间:2018-03-01 17:40:29

标签: spring-boot rabbitmq

我已经通过application.yaml和spring configurationProperties配置了我的兔子属性。 因此,当我配置交换,队列和绑定时,我可以使用我的属性的getter

@Bean Binding binding(Queue queue, TopicExchange exchange) {
    return BindingBuilder.bind(queue).to(exchange).with(properties.getQueue());
}

@Bean Queue queue() {
    return new Queue(properties.getQueue(), true);
}

@Bean TopicExchange exchange() {
    return new TopicExchange(properties.getExchange());
}

但是,当我配置@RabbitListener来记录队列中的消息时,我必须使用完整的属性名称,如

 @RabbitListener(queues = "${some.long.path.to.the.queue.name}") 
 public void onMessage(
            final Message message, final Channel channel) throws Exception {
       log.info("receiving message: {}#{}", message, channel);
    }

我想避免这种容易出错的硬编码字符串,并引用configureProperties bean,如:

@RabbitListener(queues = "${properties.getQueue()}") 

我使用@EventListener进行了一次similar issue,其中使用了bean引用" @ bean.method()"帮助,但它在这里不起作用,bean表达式只是被解释为队列名称,因为队列namde" @bean ...."不存在。

是否可以使用ConfigurationProperty-Beans进行RabbitListener队列配置?

4 个答案:

答案 0 :(得分:1)

我终于可以通过使用@David Diehl的建议,使用bean和SpEL来完成我们俩想要做的事情;但是,请改用MyRabbitProperties本身。我在配置类中删除了@EnableConfigurationProperties(MyRabbitProperties.class),并以标准方式注册了bean:

@Configuration
//@EnableConfigurationProperties(RabbitProperties.class)
@EnableRabbit
public class RabbitConfig {
  //private final MyRabbitProperties myRabbitProperties;

  //@Autowired
  //public RabbitConfig(MyRabbitProperties myRabbitProperties) {
    //this.myRabbitProperties = myRabbitProperties;
  //}      

  @Bean 
  public TopicExchange myExchange(MyRabbitProperties myRabbitProperties) {
    return new TopicExchange(myRabbitProperties.getExchange());
  }

  @Bean
  public Queue myQueueBean(MyRabbitProperties myRabbitProperties) {
    return new Queue(myRabbitProperties.getQueue(), true);
  }

  @Bean 
  public Binding binding(Queue myQueueBean, TopicExchange myExchange, MyRabbitProperties myRabbitProperties) {
    return BindingBuilder.bind(myQueueBean).to(myExchange).with(myRabbitProperties.getRoutingKey());
  }

  @Bean
  public MyRabbitProperties myRabbitProperties() {
    return new MyRabbitProperties();
  }
}

从那里,您可以访问该字段的get方法:

@Component
public class RabbitQueueListenerClass {

  @RabbitListener(queues = "#{myRabbitProperties.getQueue()}") 
  public void processMessage(Message message) {

  }
}

答案 1 :(得分:0)

在我刚使用Bean和SpEL的情况下,类似的东西对我有用。

@Autowired
Queue queue;

@RabbitListener(queues = "#{queue.getName()}")

答案 2 :(得分:0)

@RabbitListener(queues = "#{myQueue.name}") 

答案 3 :(得分:0)

听众:

@RabbitListener(queues = "${queueName}")

application.properties:

queueName=myQueue