complete jms:listener migration to JavaConfig

2019-05-10 15:52发布

问题:

Like the title says..

I have read this valuable How to add multiple JMS MessageListners in a single MessageListenerContainer for Spring Java Config link

The author of that post is working through

messageListenerContainer.setMessageListener(new TaskFinished());

BTW: I use

@Autowired
private ConsumerListener consumerListener;

defaultMessageListenerContainer.setMessageListener(consumerListener);

I am not using the new operator.

OK, the restriction of the setMessageListener method is: the class must implements the MessageListener interface, I have tested and works

My problem is, according with 23.6 JMS Namespace Support

How represent the following:

<jms:listener destination="queue.orders" ref="orderService" method="placeOrder"/>
<jms:listener destination="queue.confirmations" ref="confirmationLogger" method="log"/>

through JavaConfig?

They are simple pojo (see the ref and method attributes)

I want use how an option a simple pojo (@Component or @Service) instead of a MessageListener object

In the DefaultMessageListenerContainer API, there is no something to work around this requirement or situation.

Thanks in advance..

回答1:

<jms:listener destination="queue.orders" ref="orderService" method="placeOrder"/>

This xml uses a MessageListenerAdapter which you can hand a delegate (the ref and a method to execute (default 'handleMessage`).

@Configuration
public MyJmsConfiguration {

    @Bean
    public DefaultMessageListenerContainer consumerJmsListenerContainer() {

        DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
        ...
        MessageListenerAdapter listener = new MessageListenerAdapter();
        listener.setDelegate(orderService());
        listener.setDefaultListenerMethod("placeOrder");
        dmlc.setMessageListener(listener);
        return dmlc;
}

To use it from Java config use something like the snippet above.