eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

eBook – Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

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>io.openliberty.tools</groupId>
    <artifactId>liberty-maven-plugin</artifactId>
    <version>3.10.3</version>
    <configuration>
        <assemblyArtifact>
            <groupId>io.openliberty</groupId>
            <artifactId>openliberty-runtime</artifactId>
            <version>23.0.0.5</version>
            <type>zip</type>
        </assemblyArtifact>
        <serverXmlFile>${basedir}/src/main/liberty/config/server.xml</serverXmlFile>
        <packageName>${package.name}</packageName>
        <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</goal>
                <goal>install-feature</goal>
            </goals>
        </execution>
        <execution>
            <id>package-server-with-apps</id>
            <phase>package</phase>
            <goals>
                <goal>package</goal>
            </goals>
        </execution>
    </executions>
</plugin>

This plugin is configurable through a set of properties:

<properties>
    <!--...-->
    <app.name>library</app.name>
    <package.name>${app.name}-service</package.name>
    <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 backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
eBook – eBook Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)