I just announced the new Spring 5 modules in REST With Spring:


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 Java EE WebProfile APIs, so we can build MicroProfile applications like we build Java 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:


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:

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.


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:

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:

public class BookEndpoint {

    private BookManager bookManager;
    public Response getBook(@PathParam("id") String id) {
        return Response.ok(bookManager.get(id)).build();
    public Response getAllBooks() {
        return Response.ok(bookManager.getAll()).build();
    public Response add(Book book) {
        String bookId = bookManager.add(book);
        return Response.created(

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.


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:

public class BookMessageBodyReader implements MessageBodyReader<Book> {

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

    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:

public class BookMessageBodyWriter 
  implements MessageBodyWriter<Book> {
    public boolean isWriteable(
      Class<?> type, Type genericType, 
      Annotation[] annotations, 
      MediaType mediaType) {
        return type.equals(Book.class);
    // ...
    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);

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">
    <httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
      id="defaultHttpEndpoint" host="*"/>
    <applicationManager autoExpand="true"/>
    <webApplication context-root="${app.context.root}" location="${app.location}"/>

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

<?xml version="1.0" encoding="UTF-8"?>

This plugin is configurable throw a set of 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:

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

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.

I just announced the new Spring 5 modules in REST With Spring:


Leave a Reply

4 Comments on "Building Microservices with Eclipse MicroProfile"

newest oldest most voted
Notify of

Wow, This is article is great. I guess this is the first time I see an article about Microprofile that goes from the setup to the deploy. Thank you a lot!

It’d be cool if you could do another part now showing how they control security in MicroProfile 🙂

Thanks again!

Loredana Crusoveanu

Hey Fanime,

Interesting suggestion. We’ll add it to our content calendar 🙂


Hey Famine,
The article is about building the microservice. There are other components that make it ready for the prod.

The security is treated with the MicroProfile JWT Authentication witch could be a nice candidate for an other article.

Rolando Galindo

I crossed over MicroProfile and I was looking for a good HowTo to start with it. Thank you for posting the full example in GitHub. I have to say is really easy to follow.