Use JMS in Spring to access Azure Service Bus

This tutorial demonstrates how to use Spring Boot Starter for Azure Service Bus JMS to send messages to and receive messages from Service Bus queues and topics.

Azure provides an asynchronous messaging platform called Azure Service Bus ("Service Bus") that is based on the Advanced Message Queueing Protocol 1.0 ("AMQP 1.0") standard. You can use Service Bus across the range of supported Azure platforms.

The Spring Boot Starter for Azure Service Bus JMS provides Spring JMS integration with Service Bus.

The following video describes how to integrate Spring JMS applications with Azure Service Bus using JMS 2.0.


In this tutorial, we include two authentication methods: Microsoft Entra authentication and Shared Access Signatures (SAS) authentication. The Passwordless tab shows the Microsoft Entra authentication and the Connection string tab shows the SAS authentication.

Microsoft Entra authentication is a mechanism for connecting to Azure Service Bus JMS using identities defined in Microsoft Entra ID. With Microsoft Entra authentication, you can manage database user identities and other Microsoft services in a central location, which simplifies permission management.

SAS authentication uses the connection string of your Azure Service Bus namespace for the delegated access to Service Bus JMS. If you choose to use Shared Access Signatures as credentials, you need to manage the connection string by yourself.

Prerequisites

Important

Spring Boot version 2.5 or higher is required to complete the steps in this tutorial.

Send and receive messages from Azure Service Bus

With a queue or topic for Azure Service Bus, you can send and receive messages using Spring Cloud Azure Service Bus JMS.

To install the Spring Cloud Azure Service Bus JMS Starter module, add the following dependencies to your pom.xml file:

  • The Spring Cloud Azure Bill of Materials (BOM):

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.azure.spring</groupId>
          <artifactId>spring-cloud-azure-dependencies</artifactId>
          <version>5.11.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    Note

    If you're using Spring Boot 2.x, be sure to set the spring-cloud-azure-dependencies version to 4.17.0. This Bill of Material (BOM) should be configured in the <dependencyManagement> section of your pom.xml file. This ensures that all Spring Cloud Azure dependencies are using the same version. For more information about the version used for this BOM, see Which Version of Spring Cloud Azure Should I Use.

  • The Spring Cloud Azure Service Bus JMS Starter artifact:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-servicebus-jms</artifactId>
    </dependency>
    

Code the application

Use the following steps to configure your application to use a Service Bus queue or topic to send and receive messages.

  1. Configure the Service Bus credentials by adding the following properties to your application.properties file.

    Note

    Azure Service Bus JMS supports using Microsoft Entra ID to authorize requests to Service Bus resources. With Microsoft Entra ID, you can use Azure role-based access control (Azure RBAC) to grant permissions to a security principal, which may be a user or an application service principal.

    Important

    Before you start, ensure that you've assigned the Azure Service Bus Data Owner role to the Microsoft Entra account you're currently using. For more information, see Assign Azure roles using the Azure portal.

    spring.jms.servicebus.namespace=<ServiceBusNamespace>
    spring.jms.servicebus.pricing-tier=<ServiceBusPricingTier>
    spring.jms.servicebus.passwordless-enabled=true
    spring.jms.listener.receive-timeout=60000
    

    The following table describes the fields in the configuration:

    Field Description
    spring.jms.servicebus.namespace Specify the namespace you obtained in your Service Bus service instance from the Azure portal.
    spring.jms.servicebus.pricing-tier Specify the pricing tier of your service bus. Supported values are premium and standard. Premium tier uses Java Message Service (JMS) 2.0, while standard tier use JMS 1.1 to interact with Azure Service Bus.
    spring.jms.servicebus.passwordless-enabled Specify whether to use passwordless.
    spring.jms.listener.receive-timeout By default the receive timeout value is 1000. We recommend that you set it to 60000
  2. Add @EnableJms to enable support for JMS listener annotated endpoints. Use JmsTemplate to send messages and @JmsListener to receive messages, as shown in the following example:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.jms.annotation.EnableJms;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.jms.annotation.JmsListener;
    import org.springframework.jms.core.JmsTemplate;
    
    @SpringBootApplication
    @EnableJms
    public class ServiceBusJMSQueueApplication implements CommandLineRunner {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(ServiceBusJMSQueueApplication.class);
        private static final String QUEUE_NAME = "<QueueName>";
    
        @Autowired
        private JmsTemplate jmsTemplate;
    
        public static void main(String[] args) {
            SpringApplication.run(ServiceBusJMSQueueApplication.class, args);
        }
    
        @Override
        public void run(String... args) {
            LOGGER.info("Sending message");
            jmsTemplate.convertAndSend(QUEUE_NAME, "Hello World");
        }
    
        @JmsListener(destination = QUEUE_NAME, containerFactory = "jmsListenerContainerFactory")
        public void receiveMessage(String message) {
            LOGGER.info("Message received: {}", message);
        }
    
    }
    

    Replace <QueueName> with your own queue name configured in your Service Bus namespace.

    Tip

    In this tutorial, there are no authentication operations in the configurations or the code. However, connecting to Azure services requires authentication. To complete the authentication, you need to use Azure Identity. Spring Cloud Azure uses DefaultAzureCredential, which the Azure Identity library provides to help you get credentials without any code changes.

    DefaultAzureCredential supports multiple authentication methods and determines which method to use at runtime. This approach enables your app to use different authentication methods in different environments (such as local and production environments) without implementing environment-specific code. For more information, see DefaultAzureCredential.

    To complete the authentication in local development environments, you can use Azure CLI, Visual Studio Code, PowerShell, or other methods. For more information, see Azure authentication in Java development environments. To complete the authentication in Azure hosting environments, we recommend using user-assigned managed identity. For more information, see What are managed identities for Azure resources?

  3. Start the application. You should see Sending message and Hello World posted to your application log, as shown in the following example output:

    Sending message
    Message received: Hello World
    

Deploy to Azure Spring Apps

Now that you have the Spring Boot application running locally, it's time to move it to production. Azure Spring Apps makes it easy to deploy Spring Boot applications to Azure without any code changes. The service manages the infrastructure of Spring applications so developers can focus on their code. Azure Spring Apps provides lifecycle management using comprehensive monitoring and diagnostics, configuration management, service discovery, CI/CD integration, blue-green deployments, and more. To deploy your application to Azure Spring Apps, see Deploy your first application to Azure Spring Apps.

Next steps