Julian Herbold
Julian Herbold

Reputation: 537

JMS - message listener onMessage has to be implemented twice?

I try to add a message listener using activemq. All examples I came across use nested onMessages. Java eclipse does not allow this as I found out (also on stackoverflow). So now I am confused how to set it up. When I delete the onMessage form the listener, Eclipse tells me that I have to implement it there. In addition, it wants me to implement the onMessage method also within the class. So I have the onMessage within the listener object and within the class. How can I handle this properly? I dont see a solution where I have one onMessage in my code.

EDIT: the code is running without error and recevies messages. Still it is strange to have two onMessages

public static class HelloWorldConsumer implements Runnable, MessageListener {

        @Override
        public void run() {
            // TODO Auto-generated method stub




            // Create a Connection
            try {

                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
                Connection connection = connectionFactory.createConnection();
                connection.start();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Topic topic = session.createTopic("Physical");
                MessageConsumer consumer = session.createConsumer(topic);


                MessageListener listner = new MessageListener() {
                    @Override
                    public void onMessage(Message message) {
                        try {
                            if (message instanceof TextMessage) {
                                TextMessage textMessage = (TextMessage) message;
                                System.out.println("Received message : "
                                        + textMessage.getText() + "'");
                            }
                        } catch (JMSException e) {
                            System.out.println("Caught:" + e);
                        }
                    }
                };
                consumer.setMessageListener(listner);
                try {
                    System.in.read();
                } catch (IOException e) {
                }
                connection.close();
            } catch (JMSException ex) {
                // Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);

            }
        }//end method

        @Override
        public void onMessage(Message arg0) {
            // TODO Auto-generated method stub







        }

    }}  

Upvotes: 0

Views: 1028

Answers (1)

Nicholas
Nicholas

Reputation: 16066

Since you are creating a MessageListener as an anonymous class in-line, the class HelloWorldConsumer does not need to implement MessageListener.

Upvotes: 1

Related Questions