【问题标题】:spring pass value from property file to annotation弹簧将值从属性文件传递到注释
【发布时间】:2015-11-14 14:27:51
【问题描述】:

我有 spring 应用程序的 application.properties 文件,其中包含一些简单的属性:

queue=my.test.q

在 java 代码中我需要将队列指定给@RabbitListener:

@Component
public class Handler {    
    @RabbitListener(queues = "my.test.q")
    public void handleMessage(Message message) {
       ...
    }

这会起作用,但我想将参数传递给注释,我尝试了以下但没有一个起作用。

    @Component
    public class Handler {
        @Value("${queue}")
        private String queueName;

        @RabbitListener(queues = @Value("${queue}")  <-- not working
        @RabbitListener(queues = queueName))     <--- not working
        public void handleMessage(Message message) {
           ...
        }    

有可能吗?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    正如您在javadoc for the @RabbitListener annotation 中看到的,queues 属性是一个字符串表,因此您不能为其分配注释。您也不能在 Java 中将变量分配给注释属性,因为它们必须是 compile constants

    我现在无法对其进行测试,但 javadoc 似乎表明这应该可以工作(注意,它说它可能会返回 SpEL 表达式):

    @RabbitListener(queues = "${queue}")     
    public void handleMessage(Message message) {
        ...
    }    
    

    【讨论】:

    • @RabbitListener(queues = "${queue}")) 有额外的右括号!请删除,我没有编辑权限:)
    • 很好,已删除:)
    • 这个建议确实有效。您只需在括号中添加一个应用程序属性(也可以使用点,例如 my.application.property),它可以用作占位符
    猜你喜欢
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2012-02-14
    • 2017-04-22
    • 2015-12-15
    • 1970-01-01
    相关资源
    最近更新 更多