Agile / XP Cloud Native test driven development

Deploying to Azure Spring Cloud


Overview

This guide will walk you through the process of deploying a Spring application to Azure Spring Cloud Enterprise.

It is designed to provide an introductory look into deploying a Spring application to Azure Spring Cloud with little to no experience using Spring Framework or Microsoft Azure specifically Azure Spring Cloud Enterprise. At Enfuse, we code using Test Driven Development so this guide will adhere to that philosophy as well.

To begin let’s open your favorite IDE and have some fun.

What you will build

You will build a Spring application with a REST service that accepts an HTTP GET request at http://localhost:8080/

It will respond with a string on the landing page to display :

Hello from Spring.

You will then deploy the application you built to Azure Spring Cloud Enterprise using IntelliJ.

What you will need

Guide guidance

This guide is constructed to start from the ground up. If your more familiar with Spring and would like to skip the initialization of the project I will include a link to the repository that you can clone the code from if you like.

Starting with Spring

There are many ways of generating a new Spring project. One of the easiest and my favorite is by utilizing https://start.spring.io.

You can use this pre-initialized project and click Generate to download a ZIP file. This project has been configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.
  2. Choose Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
  3. Click Dependencies and select Spring Web.
  4. Click Generate.
  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
Example Spring initializr

Create REST Controller

Now that we have our Spring project setup and imported into IntelliJ, we can begin coding.

First we want to think about what we need, so we can determine what test we need to write.

In this example, we want a GET request to call our root path / to return a String response.

Let’s start by creating our Test Class.

  • Navigate to src/test/java/<your package name >. Then, right click <your package name>, new > Java Class. We will name this class ‘Java Class Name’ + Test.
  • Since you are testing Rest controllers, you want to tell Spring to boot your application when running tests. To do this, we will annotate our new test class with @SpringBootTest. You will also add the annotation @AutoConfigureMockMvc in order to execute the mock HTTP requests.
  • Now you need to @Autowired your MockMvc object so that it is accessible when the test is run.
  • Next, mark each test in Spring with the annotation @Test , then call the mockMvc object instantiated earlier to perform the REST GET call to our REST controller class. Test that the response is equal to what we expect. (This test should fail)

The end result of your test class should look something similar to this:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


@AutoConfigureMockMvc
@SpringBootTest
public class MyRestControllerTest {
    @Autowired
    MockMvc mockMvc;

    @Test
    public void helloTest() throws Exception {
        String testString = mockMvc.perform(get("/"))
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
        assertEquals("Hello from Spring.", testString);
    }
}

Now that you have a failing test, you can implement the minimum viable product(MVP) needed to get the test to pass.

To begin, create a REST Controller class

  • Navigate to src/main/java/<your package name > right click > new > Java Class , and make sure to name it what your test class pair is expecting. (It won’t break your code, but you will be making your code confusing by not maintaining consistent naming principles)
  • In order to tell Spring that you are creating a REST controller class, annotate the class with @RestController.
  • Now you can create your Controller method. We are creating a GET request, so we need a @GetMapping method to receive our request and process it, returning the String "Hello from Spring.".

Your final result should look something similar to this:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyRestController {

    @GetMapping("/")
    public String hello(){
        return new String("Hello from Spring.");
    }
}

Save your code we are done for now.

Configuring Azure Spring Applications

It’s time to login to the Microsoft Azure portal. After login, you can search for Azure Spring Apps, the service from Azure that you will be utilizing to accomplish cloud deployment of your code.

Create a Service Resource Group

The first requirement is to create a Service Resource Group for your Application to pull resources from when it’s deployed.

You can accomplish this by :

  • Selecting the create option in the top left corner of the landing page when navigating to Azure Spring Apps.
    • You will be taken through a creation wizard, otherwise known in the Azure community as resource blades. Each blade has different information regarding the resource group you are creating. For simplicity, in this example the first blade is the only one you need to adjust. Everything else can remain on the defaults.
  • You will be required to select a subscription. Select whichever subscription you chose earlier.
  • You will create a new Resource Group, which is Azure’s method of containerizing resources.
    • It is the best practice to create a new group for each deployment.
  • You will need to name your service, and enter a region.
    • When selecting your region, you should pick the region that’s closest to your customers (which is yourself in this case).
  • You don’t need to touch zone redundant, so leave that unchecked.
  • Your pricing should be defaulted to what your subscription allows you to have.

After you finish filling in the from you can select the “review and create” button at the bottom of the screen and generate your new resource group.

Deployment of your App

Deploying your Spring application to your Azure Spring Cloud instance has been made easy by the Azure Toolkit Plugin on IntelliJ. After installing this plugin, you will be prompted to restart IntelliJ. Once a restart has been performed you will have a new Azure option available when you right click your root project folder. It will look like this :

Azure option added

Once here, you can select the Deploy to Azure Spring Apps in the sub-menu of Azure. You will be prompted to login using your Azure credentials, and then provided the deployment dialog box.

Artifact is the application name in your IDE that you will be deploying.

Subscription is the subscription you have currently on Azure that you would like to deploy your application under.

Spring Apps is the Resource Group name you created early in Azure.

App is the name of your application, if it’s blank just click the + symbol and leave the default selections, unless you would like to rename your application. I have renamed my App to demospringazure in the picture below.

Example deployment dialog box

Before launch is a section where you can add and remove Gradle tasks to run prior to attempting to deploy the application. It defaults with the ‘assemble’ task which is good for now. When you are happy with your selections hit Apply then Run. This will kick off your deployment, and you will see those actions being processed in the bottom window of your IntelliJ as shown below.

Gradle assemble ran first

The deployment will take a couple minutes but when it’s done you should see this on your IntelliJ.

Completed Deployment of Spring App

You don’t need to wait on the deployment status. You can go to your Azure instance and verify your application has been successfully deployed.

Your Azure Cloud Spring Boot Application

So now you have deployed your application to Azure, you need to find the URL to visit your site.

In order to find your URL, first navigate back to the Azure portal and into the Azure Spring Apps service. Once there, you need to click into the resource group name that you created. You will be shown a menu on the left hand screen which displays all of the options you can explore inside your resource group. The one you are interested in is Apps under Settings. Once selected you will see your application name and some other details regarding your deployment.

Click on your application name.

In your application view you have additional menu options on the left hand side, but for now let’s focus on the Overview section. In this section Azure provides a link to your URL. If this field is empty, all you have to do is click Assign endpoint at the top of the page. If you did everything right it should look something like this.

Spring App with assigned endpoint

Now we can click the URL provided and view our application

Working Azure Spring Cloud Application

Summary

Let’s recap what you accomplished.

  • Created a Spring Application using Test Driven Development.
  • Configured Azure Spring Apps and created a Resource Group to deploy to.
  • Successfully deployed a Spring application to Azure Spring Cloud

Congratulations you’ve accomplished a lot in such a short amount of time! Enfuse will be continuing this series with another guide on how to deploy Spring applications with a Continuous Integration/Continuous Deployment(CI/CD) pipeline, stay tuned!


Useful Resources and other guides

Spring REST Guide

Microsoft Azure Documentation

Author

Travis Louloudis