SoFunction
Updated on 2025-04-08

Spring Jms Module Case Explanation

In modern distributed systems, Message Queue (MQ) plays a crucial role. It not only decouples the system's modules, but also improves the system's scalability and reliability. JMS (Java Message Service) provides a standard messaging API for Java applications as part of the Java EE specification. However, the JMS native API is relatively complex and involves many underlying operations, andSpring-JMSThe emergence of modules greatly simplifies the use of JMS in Spring applications, making the sending and receiving of messages more intuitive and easy to maintain.

This article will deeply analyze the Spring-JMS module, introduce its core functions, and use ActiveMQ as a message broker to provide a complete example of XML-based configuration to help developers quickly grasp how Spring-JMS is used.

1. Introduction to Spring-Jms module

1.1. Overview of Spring-Jms module

The Spring JMS module is a module designed to simplify the use of messaging services in Spring applications. It provides support for JMS (Java Message Service) specifications, allowing developers to easily send and receive messages and interact with message brokers (such as ActiveMQ, RabbitMQ, etc.).

The Spring JMS module simplifies the configuration of message producers and consumer endpoints, and also integrates Spring's transaction management mechanism, making the message-driven architecture easier to implement and manage.

1.2. Spring-Jms module dependency

There are four dependencies of the Spring-Tx module, namely the Spring-Beans module, the Spring-Core module, the Spring-Tx module and the Spring-Messaging module.

Among them, the Spring Beans module is a module that defines Spring Beans and implements basic IOC functions. Spring-Core is the basic module in Spring that provides the core functionality necessary for the framework to run. The Spring Tx module is a module in Spring that handles transaction management.

The primary Messaging module mainly focuses on the abstract processing of messages, supports multiple messaging protocols, and particularly strengthens support for reactive programming models, allowing developers to more conveniently create high-performance, scalable distributed systems.

1.3. Spring-Jms module function

The core role of Spring-JMS:

  • Simplify JMS API operations: Spring-JMS provides a set of template tools (e.g.JmsTemplate), encapsulates details such as connection and session management, making sending and receiving messages more convenient.
  • Support Message-Driven: Provides@JmsListenerAnnotation: The method can be declared as a JMS message listener and it will automatically trigger when receiving messages.
  • Support transaction management: Integrates transaction management with Spring, supports declarative transactions, ensuring consistency and reliability of messages when consumed.
  • Integration with Spring IoC containers: allows the use of Spring configuration to manage components such as JMS connection factory (ConnectionFactory), destination (Queue/Topic), message listening containers.
  • Support Message Conversion: ProvidesMessageConverterMechanism that supports automatic conversion of objects to JMS message formats (such as JSON, XML).
  • Supports multiple JMS providers: It can be integrated with message middleware such as ActiveMQ, Artemis, RabbitMQ (via JMS-compatible interface).

2. Spring-JMS case

This case demonstrates how to use Spring-JMS for messaging in Spring, based on ActiveMQ as a message broker.

2.1. Add dependencies

existAdd Spring-JMS and ActiveMQ related dependencies to:

<dependencies>
    <!-- Spring Core rely -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.39</version>
    </dependency>
    <!-- Spring JMS rely -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-jms</artifactId>
        <version>5.3.39</version>
    </dependency>
    <!-- ActiveMQ rely -->
    <dependency>
        <groupId></groupId>
        <artifactId>activemq-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>
    <!-- JMS API rely -->
    <dependency>
        <groupId></groupId>
        <artifactId>-api</artifactId>
        <version>2.0.1</version>
    </dependency>
</dependencies>

2.2. Configure Spring XML()

Use XML configuration files to define connection factories, JmsTemplate, listeners, etc.:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xmlns:jms="/schema/jms"
       xsi:schemaLocation="
        /schema/beans /schema/beans/
        /schema/jms /schema/jms/">
    <!-- Configuration ActiveMQ Connecting the factory -->
    <bean  class="">
        &lt;constructor-arg value="tcp://localhost:61616"/> <!-- ActiveMQ Server Address -->    &lt;/bean&gt;
    &lt;!-- Configuration JMS template --&gt;
    &lt;bean  class=""&gt;
        &lt;property name="connectionFactory" ref="connectionFactory"/&gt;
    &lt;/bean&gt;
    &lt;!-- Configuration消息Listener容器 --&gt;
    &lt;bean  class=""&gt;
        &lt;property name="connectionFactory" ref="connectionFactory"/&gt;
        &lt;property name="destinationName" value=""/&gt;
        &lt;property name="messageListener" ref="messageReceiver"/&gt;
    &lt;/bean&gt;
    &lt;!-- Message Consumers(Listener) --&gt;
    &lt;bean  class=""/&gt;
&lt;/beans&gt;

2.3. Create a message producer (Producer)

Use JmsTemplate to send messages:

package ;
import ;
import ;
public class MessageSender {
    private JmsTemplate jmsTemplate;
    private Queue queue;
    // Construct method injection    public MessageSender(JmsTemplate jmsTemplate, Queue queue) {
         = jmsTemplate;
         = queue;
    }
    public void sendMessage(String message) {
        ("Send a message:" + message);
        (queue, message);
    }
}

2.4. Create a message consumer

accomplishMessageListenerInterface to listen to messages:

package ;
import ;
import ;
import ;
public class MessageReceiver implements MessageListener {
    @Override
    public void onMessage(Message message) {
        try {
            if (message instanceof TextMessage) {
                String text = ((TextMessage) message).getText();
                ("Received the message:" + text);
            }
        } catch (Exception e) {
            ();
        }
    }
}

2.5. Start Spring context and send a message

package ;
import ;
import ;
import ;
import ;
public class JmsApp {
    public static void main(String[] args) {
        // Load Spring XML configuration        ApplicationContext context = new ClassPathXmlApplicationContext("");
        // Get JmsTemplate and queue        JmsTemplate jmsTemplate = (JmsTemplate) ("jmsTemplate");
        Queue queue = (Queue) ("testQueue");
        // Send a message        MessageSender sender = new MessageSender(jmsTemplate, queue);
        ("Hello, Spring-JMS!");
        ("Message sent!");
    }
}

2.6. Start ActiveMQ

Ensure ActiveMQStarted

activemq start

Default Web console address (you can view queue messages):

http://localhost:8161/admin

Default username/password:

admin / admin

2.7. Operation process

  • Start the ActiveMQ server first.
  • runJmsAppSend a message.
  • MessageReceiverListen to the message and print to the console.

X, afterword

In this article, we introduce in detail the role, dependency structure of the Spring-JMS module and how to integrate ActiveMQ in a non-Spring Boot environment to realize the sending and consumption of messages. By using Spring-JMS, developers can manage message communication more efficiently and integrate seamlessly with the Spring ecosystem, such as combining transaction management, message conversion and other features to further improve the robustness and maintainability of the system.

In actual projects, we can build a more efficient asynchronous message processing system based on Spring-JMS combined with other MQ components (such as RabbitMQ and Kafka). If you are interested in Spring message-driven architecture, you can further learn Spring Cloud Stream to achieve a more flexible event-driven model under the microservice architecture. I hope this article can help you better understand Spring-JMS and use it flexibly in your project!

This is the end of this article about the case explanation of Spring Jms module. For more related Spring Jms module content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!