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 – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

Spring 5 introduced WebFlux, a new framework that lets us build web applications using the reactive programming model.

In this tutorial, we’ll see how we can apply this programming model to functional controllers in Spring MVC.

2. Maven Setup

We’ll be using Spring Boot to demonstrate the new APIs.

This framework supports the familiar annotation-based approach of defining controllers. But it also adds a new domain-specific language that provides a functional way of defining controllers.

From Spring 5.2 onwards, the functional approach will also be available in the Spring Web MVC framework. As with the WebFlux module, RouterFunctions and RouterFunction are the main abstractions of this API.

So let’s start by importing the spring-boot-starter-web dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3. RouterFunction vs @Controller

In the functional realm, a web service is referred to as a route and the traditional concept of @Controller and @RequestMapping is replaced by a RouterFunction.

To create our first service, let’s take an annotation-based service and see how it can be translated into its functional equivalent.

We’ll use the example of a service that returns all the products in a product catalog:

@RestController
public class ProductController {

    @RequestMapping("/product")
    public List<Product> productListing() {
        return ps.findAll();
    }
}

Now, let’s look at its functional equivalent:

@Bean
public RouterFunction<ServerResponse> productListing(ProductService ps) {
    return route().GET("/product", req -> ok().body(ps.findAll()))
      .build();
}

3.1. The Route Definition

We should note that in the functional approach, the productListing() method returns a RouterFunction instead of the response body. It’s the definition of the route, not the execution of a request.

The RouterFunction includes the path, the request headers, a handler function, which will be used to generate the response body and the response headers. It can contain a single or a group of web services.

We’ll cover groups of web services in more detail when we look at Nested Routes.

In this example, we’ve used the static route() method in RouterFunctions to create a RouterFunction. All the requests and response attributes for a route can be provided using this method.

3.2. Request Predicates

In our example, we use the GET() method on route() to specify this is a GET request, with a path provided as a String.

We can also use the RequestPredicate when we want to specify more details of the request.

For example, the path in the previous example can also be specified using a RequestPredicate as:

RequestPredicates.path("/product")

Here, we’ve used the static utility RequestPredicates to create an object of RequestPredicate.

3.3. Response

Similarly, ServerResponse contains static utility methods that are used to create the response object.

In our example, we use ok() to add an HTTP Status 200 to the response headers and then use the body() to specify the response body.

Additionally, ServerResponse supports the building of response from custom data types using EntityResponse. We can also use Spring MVC’s ModelAndView via RenderingResponse.

3.4. Registering the Route

Next, let’s register this route using the @Bean annotation to add it to the application context:

@SpringBootApplication
public class SpringBootMvcFnApplication {

    @Bean
    RouterFunction<ServerResponse> productListing(ProductController pc, ProductService ps) {
        return pc.productListing(ps);
    }
}

Now, let’s implement some common use cases we come across while developing web services using the functional approach.

4. Nested Routes

It’s quite common to have a bunch of web services in an application and also have them divided into logical groups based on function or entity. For example, we may want all services related to a product, to begin with,/product.

Let’s add another path to the existing path /product to find a product by its name:

public RouterFunction<ServerResponse> productSearch(ProductService ps) {
    return route().nest(RequestPredicates.path("/product"), builder -> {
        builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name"))));
    }).build();
}

In the traditional approach, we’d have achieved this by passing a path to @Controller. However, the functional equivalent for grouping web services is the nest() method on route().

Here, we start by providing the path under which we want to group the new route, which is /product. Next, we use the builder object to add the route similarly as in the previous examples.

The nest() method takes care of merging the routes added to the builder object with the main RouterFunction.

5.  Error Handling

Another common use case is to have a custom error handling mechanism. We can use the onError() method on route() to define a custom exception handler.

This is equivalent to using the @ExceptionHandler in the annotation-based approach. But it is far more flexible since it can be used to define separate exception handlers for each group of routes.

Let’s add an exception handler to the product search route we created earlier to handle a custom exception thrown when a product is not found:

public RouterFunction<ServerResponse> productSearch(ProductService ps) {
    return route()...
      .onError(ProductService.ItemNotFoundException.class,
         (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
           .status(HttpStatus.NOT_FOUND)
           .build())
      .build();
}

The onError() method accepts the Exception class object and expects a ServerResponse from the functional implementation.

We have used EntityResponse which is a subtype of ServerResponse to build a response object here from the custom datatype Error. We then add the status and use EntityResponse.build() which returns a ServerResponse object.

6. Filters

A common way of implementing authentication as well as managing cross-cutting concerns such as logging and auditing is using filters. Filters are used to decide whether to continue or abort the processing of the request.

Let’s take an example where we want a new route that adds a product to the catalog:

public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
    return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
      .onError(IllegalArgumentException.class, 
         (e, req) -> EntityResponse.fromObject(new Error(e.getMessage()))
           .status(HttpStatus.BAD_REQUEST)
           .build())
        .build();
}

Since this is an admin function we also want to authenticate the user calling the service.

We can do this by adding a filter() method on route():

public RouterFunction<ServerResponse> adminFunctions(ProductService ps) {
   return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class))))
     .filter((req, next) -> authenticate(req) ? next.handle(req) : 
       status(HttpStatus.UNAUTHORIZED).build())
     ....;
}

Here, as the filter() method provides the request as well as the next handler, we use it to do a simple authentication which allows the product to be saved if successful or returns an UNAUTHORIZED error to the client in case of failure.

7. Cross-Cutting Concerns

Sometimes, we may want to perform some actions before, after or around a request. For example, we may want to log some attributes of the incoming request and outgoing response.

Let’s log a statement every time the application finds a matching for the incoming request. We’ll do this using the before() method on route():

@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
    return route()...
      .before(req -> {
          LOG.info("Found a route which matches " + req.uri()
            .getPath());
          return req;
      })
      .build();
}

Similarly, we can add a simple log statement after the request has been processed using the after() method on route():

@Bean
RouterFunction<ServerResponse> allApplicationRoutes(ProductController pc, ProductService ps) {
    return route()...
      .after((req, res) -> {
          if (res.statusCode() == HttpStatus.OK) {
              LOG.info("Finished processing request " + req.uri()
                  .getPath());
          } else {
              LOG.info("There was an error while processing request" + req.uri());
          }
          return res;
      })          
      .build();
    }

8. Conclusion

In this tutorial, we started with a brief introduction to the functional approach for defining controllers. We then compared Spring MVC annotations with their functional equivalents.

Next, we implemented a simple web service that returned a list of products with a functional controller.

Then we proceeded to implement some of the common use cases for web service controllers, including nesting routes, error handling, adding filters for access control, and managing cross-cutting concerns like logging.

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)