How to use the Spring Boot Starter for Azure Storage

This article walks you through creating a custom application using the Spring Initializr, then adding the Azure storage starter to your application, and then using your application to upload a blob to your Azure storage account.

Prerequisites

The following prerequisites are required in order to follow the steps in this article:

Important

Spring Boot version 2.0 or greater is required to complete the steps in this article.

Create an Azure Storage Account and blob container for your application

The following procedure creates an Azure storage account and container.

  1. Browse to the Azure portal at https://portal.azure.com/ and sign in.

  2. Click +Create a resource, then Storage, and then click Storage Account.

    Create Azure Storage Account

  3. On the Create storage account page, enter the following information:

    • Select Subscription.
    • Select Resource group, or create a new resource group.
    • Enter a unique Storage account name, which will become part of the URI for your storage account. For example: if you entered wingtiptoysstorage for the Name, the URI would be wingtiptoysstorage.core.windows.net.
    • Specify the Location for your storage account.
  4. When you have specified the options listed above, click Review + create.

  5. Review the specification, then click Create to create your storage account.

  6. When the deployment is complete, click Go to resource.

  7. Click Containers.

  8. Click + Container.

    • Name the container.
    • Select Blob from the drop-down list.

    Create blob container

  9. The Azure portal will list your blob container after is has been created.

Create a simple Spring Boot application with the Spring Initializr

The following procedure creates the Spring boot application.

  1. Browse to https://start.spring.io/.

  2. Specify the following options:

    • Generate a Maven project.

    • Specify Java.

    • Specify a Spring Boot version that is equal to or greater than 2.0.

    • Specify the Group and Artifact names for your application.

    • Add the Web dependency.

      Basic Spring Initializr options

    Note

    The Spring Initializr uses the Group and Artifact names to create the package name; for example: com.wingtiptoys.storage.

  3. When you have specified the options listed above, click Generate.

  4. When prompted, download the project to a path on your local computer.

  5. After you have extracted the files on your local system, your simple Spring Boot application will be ready to edit.

Configure your Spring Boot app to use the Azure Storage starter

The following procedure configures the Spring boot application to use Azure storage.

  1. Locate the pom.xml file in the root directory of your app; for example:

    C:\SpringBoot\storage\pom.xml

    -or-

    /users/example/home/storage/pom.xml

  2. Open the pom.xml file in a text editor, and add the Spring Cloud Azure Storage starter to the list of <dependencies>:

    <dependency>
       <groupId>com.microsoft.azure</groupId>
       <artifactId>spring-azure-starter-storage</artifactId>
       <version>1.0.0.M2</version>
    </dependency>
    

    Edit pom.xml file

  3. Save and close the pom.xml file.

Create an Azure Credential File

The following procedure creates the Azure credential file.

  1. Open a command prompt.

  2. Navigate to the resources directory of your Spring Boot app; for example:

    cd C:\SpringBoot\storage\src\main\resources
    

    -or-

    cd /users/example/home/storage/src/main/resources
    
  3. Sign in to your Azure account:

    az login
    
  4. List your subscriptions:

    az account list
    

    Azure will return a list of your subscriptions, and you will need to copy the GUID for the subscription that you want to use; for example:

    [
      {
        "cloudName": "AzureCloud",
        "id": "11111111-1111-1111-1111-111111111111",
        "isDefault": true,
        "name": "Converted Windows Azure MSDN - Visual Studio Ultimate",
        "state": "Enabled",
        "tenantId": "22222222-2222-2222-2222-222222222222",
        "user": {
          "name": "gena.soto@wingtiptoys.com",
          "type": "user"
        }
      }
    ]
    
  5. Specify the GUID for the subscription you want to use with Azure; for example:

    az account set -s 11111111-1111-1111-1111-111111111111
    
  6. Create your Azure Credential file:

    az ad sp create-for-rbac --sdk-auth > my.azureauth
    

    This command will create a my.azureauth file in your resources directory with contents that resemble the following example:

    {
      "clientId": "33333333-3333-3333-3333-333333333333",
      "clientSecret": "44444444-4444-4444-4444-444444444444",
      "subscriptionId": "11111111-1111-1111-1111-111111111111",
      "tenantId": "22222222-2222-2222-2222-222222222222",
      "activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
      "resourceManagerEndpointUrl": "https://management.azure.com/",
      "activeDirectoryGraphResourceId": "https://graph.windows.net/",
      "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
      "galleryEndpointUrl": "https://gallery.azure.com/",
      "managementEndpointUrl": "https://management.core.windows.net/"
    }
    

Configure your Spring Boot app to use your Azure Storage account

The following procedure configures the Spring boot application to use your Azure storage account.

  1. Locate the application.properties in the resources directory of your app; for example:

    C:\SpringBoot\storage\src\main\resources\application.properties

    -or-

    /users/example/home/storage/src/main/resources/application.properties

  2. Open the application.properties file in a text editor, add the following lines, and then replace the sample values with the appropriate properties for your storage account:

    spring.cloud.azure.credential-file-path=my.azureauth
    spring.cloud.azure.resource-group=wingtiptoysresources
    spring.cloud.azure.region=West US
    spring.cloud.azure.storage.account=wingtiptoysstorage
    

    Where:

    Field Description
    spring.cloud.azure.credential-file-path Specifies Azure credential file that you created earlier in this tutorial.
    spring.cloud.azure.resource-group Specifies the Azure Resource Group that contains your Azure Storage account.
    spring.cloud.azure.region Specifies the geographical region that you specified when you created your Azure Storage account.
    spring.cloud.azure.storage.account Specifies Azure Storage account that you created earlier in this tutorial.
  3. Save and close the application.properties file.

Add sample code to implement basic Azure storage functionality

In this section, you create the necessary Java classes for storing a blob in your Azure storage account.

Modify the main application class

  1. Locate the main application Java file in the package directory of your app; for example:

    C:\SpringBoot\storage\src\main\java\com\wingtiptoys\storage\StorageApplication.java

    -or-

    /users/example/home/storage/src/main/java/com/wingtiptoys/storage/StorageApplication.java

  2. Open the main application Java file in a text editor, and add the following lines to the file. Replace wingtiptoys with your values:

    package com.wingtiptoys.storage;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class StorageApplication {
       public static void main(String[] args) {
          SpringApplication.run(StorageApplication.class, args);
       }
    }
    
  3. Save and close the main application Java file.

Add a web controller class

  1. Create a new Java file named WebController.java in the package directory of your app; for example:

    C:\SpringBoot\storage\src\main\java\com\wingtiptoys\storage\WebController.java

    -or-

    /users/example/home/storage/src/main/java/com/wingtiptoys/storage/WebController.java

  2. Open the web controller Java file in a text editor, and add the following lines to the file. Change wingtiptoys to your resource group and storage to your artifact name.

    package com.wingtiptoys.storage;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.WritableResource;
    import org.springframework.util.StreamUtils;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.nio.charset.Charset;
    
    @RestController
    public class WebController {
    
       @Value("blob://test/myfile.txt")
       private Resource blobFile;
    
       @GetMapping(value = "/")
       public String readBlobFile() throws IOException {
          return StreamUtils.copyToString(
             this.blobFile.getInputStream(),
             Charset.defaultCharset()) + "\n";
       }
    
       @PostMapping(value = "/")
       public String writeBlobFile(@RequestBody String data) throws IOException {
          try (OutputStream os = ((WritableResource) this.blobFile).getOutputStream()) {
             os.write(data.getBytes());
          }
          return "File was updated.\n";
       }
    }
    

    Where the @Value("blob://[container]/[blob]") syntax respectively defines the names of the container and blob where you want to store the data.

  3. Save and close the web controller Java file.

  4. Open a command prompt and change directory to the folder where your pom.xml file is located; for example:

    cd C:\SpringBoot\storage

    -or-

    cd /users/example/home/storage

  5. Build your Spring Boot application with Maven and run it; for example:

    mvn clean package
    mvn spring-boot:run
    
  6. Once your application is running, you can use curl to test your application; for example:

    a. Send a POST request to update a file's contents:

    curl -X POST -H "Content-Type: text/plain" -d "Hello World" http://localhost:8080/
    

    You should see a response that the file was updated.

    b. Send a GET request to verify the file's contents:

    curl -X GET http://localhost:8080/
    

    You should see the "Hello World" text that you posted.

Summary

In this tutorial, you created a new Java application using the [Spring Initializr], added the Azure storage starter to your application, and then configured your application to upload a blob to your Azure storage account.

Next steps

To learn more about Spring and Azure, continue to the Spring on Azure documentation center.

Additional Resources

For more information about the additional Spring Boot Starters that are available for Microsoft Azure, see Spring Boot Starters for Azure.

For detailed information about additional Azure storage APIs that you can call from your Spring Boot applications, see the following articles: