Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically set @JmsListener destination from configuration properties

I want to be able to set the @JMSlistener destination from an application.properties

my code looks like this

@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);

    }
}

but when building I get

Error:(25, 60) java: element value must be a constant expression
like image 978
JaChNo Avatar asked Mar 19 '18 17:03

JaChNo


People also ask

What is destination in @JmsListener?

destination provides various strategies for managing JMS destinations, such as providing a service locator for destinations stored in JNDI. The package org. springframework. jms. annotation provides the necessary infrastructure to support annotation-driven listener endpoints using @JmsListener .

How to send message using JmsTemplate?

The default method for sending the message is JmsTemplate. send(). It has two key parameters of which, the first parameter is the JMS destination and the second parameter is an implementation of MessageCreator. The JmsTemplate uses the MessageCreator's callback method createMessage() for constructing the message.


2 Answers

You can't reference a field within the current bean, but you can reference another bean in the application context using a SpEL expression...

@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";
        }
    }

}

You can also use property placeholders ${...}.

like image 86
Gary Russell Avatar answered Sep 20 '22 15:09

Gary Russell


Using property placeholder is much easier.

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

}
like image 27
Chris Avatar answered Sep 23 '22 15:09

Chris