Thursday, 14 April 2011

Using Spring JmsTemplate

One very useful reoccurring Spring pattern is the use of template helpers that take hard work out of some very boring day to day stuff. The guys are Spring have provided a considerable number of template classes including JdbcTemplate, JdoTemplate and SqlMapClientTemplate. One of the most useful is the JmsTemplate, which is a way of managing JMS connections. It is incredibly flexible as it works in collaboration with several other helper classes including JndiTemplate, JndiObjectFactoryBean and JndiDestinationResolver.

This example demonstrates the strategy for setting up JmsTemplate and the first step is to configure the JndiTemplate:
 <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
  <property name="environment">
   <props>
    <prop key="java.naming.provider.url">t3://localhost:7001</prop>
    <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
   </props>
  </property>
 </bean>
The next step is to configure the connection factory:
 <bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiTemplate">
   <ref bean="jndiTemplate"/>
  </property>
  <property name="jndiName">
   <value>weblogic.jms.XAConnectionFactory</value>
  </property>
 </bean>
The JndiTemple is also used to create a destination resolver:
 <bean id="jndiResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver">
  <property name="jndiTemplate">
   <ref bean="jndiTemplate"/>
  </property>
  <property name="cache">
   <value>true</value>
  </property>
 </bean>
These are then added together to create our JmsTemplate:
 <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
  <property name="connectionFactory" ref="connectionFactory"/>
  <property name="receiveTimeout">
   <value>0</value>
  </property>
  <property name="destinationResolver" ref="jndiResolver"/>
 </bean>
The JmsTemplate can be then used in the following way:

    Message message = jmsTemplate.receive(inQueueJndiName);


This is just one way of configuring these classes, but being flexible there will be many variations you can try.

No comments: