【问题标题】:dynamically set @JmsListener destination from configuration properties从配置属性动态设置@JmsListener 目标
【发布时间】:2018-08-28 08:10:34
【问题描述】:

我希望能够从 application.properties 设置@JMSlistener 目标

我的代码是这样的

@Service
public class ListenerService {
    private Logger log = Logger.getLogger(ListenerService.class);

    @Autowired
    QueueProperties queueProperties;


    public ListenerService(QueueProperties queueProperties) {
        this.queueProperties = queueProperties;

    }

    @JmsListener(destination = queueProperties.getQueueName() )
    public void listenQueue(String requestJSON) throws JMSException {
        log.info("Received " + requestJSON);

    }
}

但是在构建时我得到了

Error:(25, 60) java: element value must be a constant expression

【问题讨论】:

  • 你可以在目的地尝试#listenerService.queueProperties.getQueueName()
  • 我得到这个错误:(25, 47) java: non-static variable queueProperties cannot be referenced from a static context
  • 你用大括号试过了吗,所以大括号中的“#{}”指定了我上面提到的内容。

标签: java spring-boot jms spring-jms jmstemplate


【解决方案1】:

您不能引用当前 bean 中的字段,但可以使用 SpEL 表达式在应用程序上下文中引用另一个 bean...

@SpringBootApplication
public class So49368515Application {

    public static void main(String[] args) {
        SpringApplication.run(So49368515Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(JmsTemplate template, Foo foo) {
        return args -> template.convertAndSend(foo.getDestination(), "test");
    }

    @JmsListener(destination = "#{@foo.destination}")
    public void listen(Message in) {
        System.out.println(in);
    }

    @Bean
    public Foo foo() {
        return new Foo();
    }

    public class Foo {

        public String getDestination() {
            return "foo";
        }
    }

}

您也可以使用属性占位符${...}

【讨论】:

  • Gary 为什么还没有实施呢?如果在 spel 中可以引用当前 bean,那真的很有帮助吗?
  • 这不是未实现的问题尚未 - Annotation 无法引用它所使用的 bean;该值必须是静态的,因为它存储在 Class 文件中。
【解决方案2】:

使用属性占位符要容易得多。

@JmsListener(destination = "${mq.queue}")
public void onMessage(Message data) {

}

【讨论】:

  • 好多了。谢谢
猜你喜欢
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多