top of page
Post: Blog2 Post
Writer's pictureNikhila Jain

How to Create Java Micronaut Microservice?

Updated: Mar 31, 2022

Micronaut is a modern, JVM based full stack framework. It gives you flexibility to build modular, easily testable microservices and serverless applications. In this tutorial, we will start from scratch, and you will learn to create, test and build your first Micronaut Microservice.


In this tutorial, you'll learn how to create your first Java Micronaut Microservice. So, let’s deep dive into it.


Why Micronaut? Micronaut gives your applications a fast startup time & low memory thresholds. It provides an out-of-the-box cloud support, fast data-access configuration for quickly writing and integrating your APIs with an in-built OpenAPI & Swagger support.

With fast & easy testing, your microservices are production ready in no time.

Build Your Micronaut Microservice

Using Micronaut you can create microservices in different languages like Java, Kotlin and Groovy. In this tutorial, you will create your first Microservice using Java and Micronaut. You will also see how easy it is to create a test that runs fast.

Prerequisites

You'll need following things to get started with the tutorial:

  • A Java Editor - Text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

  • Micronaut installed on your machine

Let’s get started with installing Micronaut on your machine.

Install Micronaut

For quick and effortless installation, you can use SDKMAN to download and configure Micronaut. You can install Micronaut using SDKMAN on any unix based platforms (MacOs, Linux, Cygwin).

Open your terminal and enter:

$ curl -s https://get.sdkman.io | bash

Open a new terminal or type the command:

$ source "$HOME/.sdkman/bin/sdkman-init.sh"

Then install the latest stable version of the framework:

$ sdk install micronaut

To check your installation is complete, type the command:

$ mn —version

You are all set to get started.

Generate Microservice

As you have Micronaut installed, it's time to get our hands dirty and create our first Micronaut Microservice.

There are two ways in which you can generate the scaffolding for your Micronaut application.


Command Line Interface

Use Micronaut Command Line interface or a web hosted Micronaut Launch utility. I will use the command line interface to create the application. Open a terminal and type the below command.

mn create-app com.micronaut.javamicroservicetutorial --build=gradle —Mn -invokes the micronaut framework 2

create-app -creates the app with the name given, in this example com.micronaut.javamicroservicetutorial.

The application is created in the directory name javamicroservicetutorial and the default package hierarchy is com.micronaut.

build

Build specifies the framework that you are using for building the application. If the build attribute is absent then by default Gradle is used as the build tool. The supported frameworks are Gradle and Maven.

lang

lang specifies the language that you want to use for creating application, in our case it is java. If you don't supply this attribute, micronaut considers Java by default. However, you can choose from Java/kotlin/groovy.

CLASS HIERARCHY

Let's take a closer look at the class hierarchy of Application.java that is the main class. You can also run this class using gradle.



package com.micronaut.controller;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller; 
import io.micronaut.http.annotation.Get; 
import io.micronaut.http.annotation.Produces;

@Controller(“/welcome”)
public class MicronautTutorialController {

    @Get @Produces(MediaType.TEXT_PLAIN)
    public String index() {

        return “Welcome to your first Micronaut Tutorial!“; 
    }
}

In the above code snippet, you can see that the root package is created as com.micronaut, which you have specified in the create-app command.

CREATE CONTROLLER

In order to communicate with your microservice, let's create a controller that will respond with a message - "Welcome to your first Micronaut Tutorial!”.


@Controller(“/welcome”)
public class MicronautTutorialController {
}

In the below code snippet, you can see that as you use annotation in spring to define a controller micronaut also uses the same annotation @Controller to define a controller class.


There are a wide range of annotations provided by Micronaut, some of the annotations used in the sample code snippet are as follows:

  • @Controller //to specify that the class is a controller

  • @Get //to specify a HTTP GET Request

  • @Produces //to specify that a result in the form text/plain that is a string will be returned when the method will be called.

By default micronaut uses application/JSON as the content type, but as we are returning a string we have explicitly set it to text/plain using MediaType.TEXT_PLAIN

Run the Application

To run the application use the below command:


./gradlew run

Now that you have the first controller and app created. Let's create a test class.


Build Tests for the Java Microservice Create the test class to verify if you get the string response.


package com.micronaut.controller;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.junit.jupiter.api.Test;
import jakarta.inject.Inject;

@MicronautTest
public class MicronautTutorialControllerTest {

    @Inject @Client("/") HttpClient client;
    
    @Test
    public void testWelcomeMessage() {
        HttpRequest<String> request = HttpRequest.GET("/welcome");
        String body = client.toBlocking().retrieve(request);
        assertNotNull(body);
        assertEquals ("Welcome to your first Micronaut Tutorial", body);
    } 
}

The above code snippet shows that you can use annotations for test class.

  • @MicronautTest- it tells micronaut framework to initialise the server.

  • @Inject- injects the HttpClient bean

  • Create an http request and trigger a call to /welcome

TEST THE APPLICATION

You can run the tests by

$ ./gradlew test

To check the reports use

$ open build/reports/tests/test/index.html

Conclusion

Micronaut’s Java microservice framework provides a complete, efficient and modular solution to build microservices in Java. If you are looking to create your own microservices, the time to start is now.


Subscribe to the mailing list to stay connected with enriching technical blogs.

Comments


bottom of page