Partner – Payara – NPI (cat=Jakarta EE)
announcement - icon

Can Jakarta EE be used to develop microservices? The answer is a resounding ‘yes’!

>> Demystifying Microservices for Jakarta EE & Java EE Developers

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this article, we’ll focus on building a microservice based on Eclipse MicroProfile.

We’ll look at how to write a RESTful web application using JAX-RS, CDI and JSON-P APIs.

2. A Microservice Architecture

Simply put, microservices are a software architecture style that forms a complete system as a collection of several independent services.

Each one focuses on one functional perimeter and communicates to the others with a language-agnostic protocol, such as REST.

3. Eclipse MicroProfile

Eclipse MicroProfile is an initiative that aims to optimize Enterprise Java for the Microservices architecture. It’s based on a subset of Jakarta EE WebProfile APIs, so we can build MicroProfile applications like we build Jakarta EE ones.

The goal of MicroProfile is to define standard APIs for building microservices and deliver portable applications across multiple MicroProfile runtimes.

4. Maven Dependencies

All dependencies required to build an Eclipse MicroProfile application are provided by this BOM (Bill Of Materials) dependency:

<dependency>
    <groupId>org.eclipse.microprofile</groupId>
    <artifactId>microprofile</artifactId>
    <version>6.0</version>
    <type>pom</type>
    <scope>provided</scope>
</dependency>

The scope is set as provided because the MicroProfile runtime already includes the API and the implementation.

5. Representation Model

Let’s start by creating a quick resource class:

public class Book {
    private String id;
    private String name;
    private String author;
    private Integer pages;
    // ...
}

As we can see, there’s no annotation on this Book class.

6. Using CDI

Simply put, CDI is an API that provides dependency injection and lifecycle management. It simplifies the use of Enterprise beans in Web Applications.

Let’s now create a CDI managed bean as a store for the book representation:

@ApplicationScoped
public class BookManager {

    private ConcurrentMap<String, Book> inMemoryStore
      = new ConcurrentHashMap<>();

    public String add(Book book) {
        // ...
    }

    public Book get(String id) {
        // ...
    }

    public List getAll() {
        // ...
    }
}

We annotate this class with @ApplicationScoped because we need only one instance whose state is shared by all clients. For that, we used a ConcurrentMap as a type-safe in-memory data store. Then we added methods for CRUD operations.

Now our bean is a CDI ready and can be injected into the bean BookEndpoint using the @Inject annotation.

7. JAX-RS API

To create a REST application with JAX-RS, we need to create an Application class annotated with @ApplicationPath and a resource annotated with @Path.

7.1. JAX RS Application

The JAX-RS Application identifies the base URI under which we expose the resource in a Web Application.

Let’s create the following JAX-RS Application:

@ApplicationPath("library")
public class LibraryApplication extends Application {
}

In this example, all JAX-RS resource classes in the Web Application are associated with the LibraryApplication making them under the same library path, that’s the value of the ApplicationPath annotation.

This annotated class tells the JAX RS runtime that it should find resources automatically and exposes them.

7.2. JAX RS Endpoint

An Endpoint class, also called Resource class, should define one resource although many of the same types are technically possible.

Each Java class annotated with @Path, or having at least one method annotated with @Path or @HttpMethod is an Endpoint.

Now, we’ll create a JAX-RS Endpoint that exposes that representation:

@Path("books")
@RequestScoped
public class BookEndpoint {

    @Inject
    private BookManager bookManager;
 
    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBook(@PathParam("id") String id) {
        return Response.ok(bookManager.get(id)).build();
    }
 
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllBooks() {
        return Response.ok(bookManager.getAll()).build();
    }
 
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response add(Book book) {
        String bookId = bookManager.add(book);
        return Response.created(
          UriBuilder.fromResource(this.getClass())
            .path(bookId).build())
            .build();
    }
}

At this point, we can access the BookEndpoint Resource under the /library/books path in the web application.

7.3. JAX RS JSON Media Type

JAX RS supports many media types for communicating with REST clients, but Eclipse MicroProfile restricts the use of JSON as it specifies the use of the JSOP-P API. As such, we need to annotate our methods with @Consumes(MediaType.APPLICATION_JSON) and @Produces(MediaType.APPLICATION_JSON).

The @Consumes annotation restricts the accepted formats – in this example, only JSON data format is accepted. The HTTP request header Content-Type should be application/json.

The same idea lies behind the @Produces annotation. The JAX RS Runtime should marshal the response to JSON format. The request HTTP header Accept should be application/json.

8. JSON-P

JAX RS Runtime supports JSON-P out of the box so that we can use JsonObject as a method input parameter or return type.

But in the real world, we often work with POJO classes. So we need a way to do the mapping between JsonObject and POJO. Here’s where the JAX RS entity provider goes to play.

For marshaling JSON input stream to the Book POJO, that’s invoking a resource method with a parameter of type Book, we need to create a class BookMessageBodyReader:

@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class BookMessageBodyReader implements MessageBodyReader<Book> {

    @Override
    public boolean isReadable(
      Class<?> type, Type genericType, 
      Annotation[] annotations, 
      MediaType mediaType) {
 
        return type.equals(Book.class);
    }

    @Override
    public Book readFrom(
      Class type, Type genericType, 
      Annotation[] annotations,
      MediaType mediaType, 
      MultivaluedMap<String, String> httpHeaders, 
      InputStream entityStream) throws IOException, WebApplicationException {
 
        return BookMapper.map(entityStream);
    }
}

We do the same process to unmarshal a Book to JSON output stream, that’s invoking a resource method whose return type is Book, by creating a BookMessageBodyWriter:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookMessageBodyWriter 
  implements MessageBodyWriter<Book> {
 
    @Override
    public boolean isWriteable(
      Class<?> type, Type genericType, 
      Annotation[] annotations, 
      MediaType mediaType) {
 
        return type.equals(Book.class);
    }
 
    // ...
 
    @Override
    public void writeTo(
      Book book, Class<?> type, 
      Type genericType, 
      Annotation[] annotations, 
      MediaType mediaType, 
      MultivaluedMap<String, Object> httpHeaders, 
      OutputStream entityStream) throws IOException, WebApplicationException {
 
        JsonWriter jsonWriter = Json.createWriter(entityStream);
        JsonObject jsonObject = BookMapper.map(book);
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();
    }
}

As BookMessageBodyReader and BookMessageBodyWriter are annotated with @Provider, they’re registered automatically by the JAX RS runtime.

9. Building and Running the Application

A MicroProfile application is portable and should run in any compliant MicroProfile runtime. We’ll explain how to build and run our application in Open Liberty, but we can use any compliant Eclipse MicroProfile.

We configure Open Liberty runtime through a config file server.xml:

<server description="OpenLiberty MicroProfile server">
    <featureManager>
        <feature>jackartaee-10</feature>
        <feature>cdi-4.0</feature>
        <feature>jsonp-2.1</feature>
    </featureManager>
    <httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
      id="defaultHttpEndpoint" host="*"/>
    <applicationManager autoExpand="true"/>
    <webApplication context-root="${app.context.root}" location="${app.location}"/>
</server>

Let’s add the plugin liberty-maven-plugin to our pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<plugin>
    <groupId>net.wasdev.wlp.maven.plugins</groupId>
    <artifactId>liberty-maven-plugin</artifactId>
    <version>2.1.2</version>
    <configuration>
        <assemblyArtifact>
            <groupId>io.openliberty</groupId>
            <artifactId>openliberty-runtime</artifactId>
            <version>23.0.0.5</version>
            <type>zip</type>
        </assemblyArtifact>
        <configFile>${basedir}/src/main/liberty/config/server.xml</configFile>
        <packageFile>${package.file}</packageFile>
        <include>${packaging.type}</include>
        <looseApplication>false</looseApplication>
        <installAppPackages>project</installAppPackages>
        <bootstrapProperties>
            <app.context.root>/</app.context.root>
            <app.location>${project.artifactId}-${project.version}.war</app.location>
            <default.http.port>9080</default.http.port>
            <default.https.port>9443</default.https.port>
        </bootstrapProperties>
    </configuration>
    <executions>
        <execution>
            <id>install-server</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>install-server</goal>
                <goal>create-server</goal>
                <goal>install-feature</goal>
            </goals>
        </execution>
        <execution>
            <id>package-server-with-apps</id>
            <phase>package</phase>
            <goals>
                <goal>install-apps</goal>
                <goal>package-server</goal>
            </goals>
        </execution>
    </executions>
</plugin>

This plugin is configurable throw a set of properties:

<properties>
    <!--...-->
    <app.name>library</app.name>
    <package.file>${project.build.directory}/${app.name}-service.jar</package.file>
    <packaging.type>runnable</packaging.type>
</properties>

The exec goal above produces an executable jar file so that our application will be an independent microservice which can be deployed and run in isolation. We can also deploy it as Docker image.

To create an executable jar, run the following command:

mvn package

And to run our microservice, we use this command:

java -jar target/library-service.jar

This will start the Open Liberty runtime and deploy our service. We can access to our Endpoint and getting all books at this URL:

curl http://localhost:9080/library/books

The result is a JSON:

[
  {
    "id": "0001-201802",
    "isbn": "1",
    "name": "Building Microservice With Eclipse MicroProfile",
    "author": "baeldung",
    "pages": 420
  }
]

To get a single book, we request this URL:

curl http://localhost:9080/library/books/0001-201802

And the result is JSON:

{
    "id": "0001-201802",
    "isbn": "1",
    "name": "Building Microservice With Eclipse MicroProfile",
    "author": "baeldung",
    "pages": 420
}

Now we’ll add a new Book by interacting with the API:

curl 
  -H "Content-Type: application/json" 
  -X POST 
  -d '{"isbn": "22", "name": "Gradle in Action","author": "baeldung","pages": 420}' 
  http://localhost:9080/library/books

As we can see, the status of the response is 201, indicating that the book was successfully created, and the Location is the URI by which we can access it:

< HTTP/1.1 201 Created
< Location: http://localhost:9080/library/books/0009-201802

10. Conclusion

This article demonstrated how to build a simple microservice based on Eclipse MicroProfile, discussing JAX RS, JSON-P and CDI.

The code is available over on Github; this is a Maven-based project, so it should be simple to import and run as it is.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Microservices (eBook) (cat=Cloud/Spring Cloud)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.