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:
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:
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:
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:
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:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
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:
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:
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.
1. Overview
Spring 5 includes Spring WebFlux, which provides reactive programming support for web applications.
In this tutorial, weβll create a small reactive REST application using the reactive web components RestController and WebClient.
Weβll also look at how to secure our reactive endpoints using Spring Security.
Further reading:
Spring WebClient
Handling Errors in Spring WebFlux
Introduction to the Functional Web Framework in Spring
2. Spring WebFlux Framework
Spring WebFlux internally uses Project Reactor and its publisher implementations, Flux and Mono.
The new framework supports two programming models:
- Annotation-based reactive components
- Functional routing and handling
Weβll focus on the annotation-based reactive components, as we already explored the functional style β routing and handling in another tutorial.
3. Dependencies
Letβs start with the spring-boot-starter-webflux dependency, which pulls in all other required dependencies:
- spring-boot and spring-boot-starter for basic Spring Boot application setup
- spring-webflux framework
- reactor-core that we need for reactive streams and also reactor-netty
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>3.5.7</version>
</dependency>
The latest spring-boot-starter-webflux can be downloaded from Maven Central.
4. Reactive REST Application
Now weβll build a very simple reactive REST EmployeeManagement application using Spring WebFlux:
- Use a simple domain model β Employee with an id and a name field
- Build a REST API with a RestController to publish Employee resources as a single resource and as a collection
- Build a client with WebClient to retrieve the same resource
- Create a secured reactive endpoint using WebFlux and Spring Security
5. Reactive RestController
Spring WebFlux supports annotation-based configurations in the same way as the Spring Web MVC framework.
To begin with, on the server, we create an annotated controller that publishes a reactive stream of the Employee resource.
Letβs create our annotated EmployeeController:
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeRepository employeeRepository;
// constructor...
}
EmployeeRepository can be any data repository that supports non-blocking reactive streams.
5.1. Single Resource
Then letβs create an endpoint in our controller that publishes a single Employee resource:
@GetMapping("/{id}")
public Mono<Employee> getEmployeeById(@PathVariable String id) {
return employeeRepository.findEmployeeById(id);
}
We wrap a single Employee resource in a Mono because we return at most one employee.
5.2. Collection Resource
We also add an endpoint that publishes the collection resource of all Employees:
@GetMapping
public Flux<Employee> getAllEmployees() {
return employeeRepository.findAllEmployees();
}
For the collection resource, we use a Flux of type Employee since thatβs the publisher for 0..n elements.
6. Reactive Web Client
WebClient, introduced in Spring 5, is a non-blocking client with support for reactive streams.
We can use WebClient to create a client to retrieve data from the endpoints provided by the EmployeeController.
Letβs create a simple EmployeeWebClient:
public class EmployeeWebClient {
WebClient client = WebClient.create("http://localhost:8080");
// ...
}
Here we have created a WebClient using its factory method create. Itβll point to localhost:8080, so we can use relative URLs for calls made by this client instance.
6.1. Retrieving a Single Resource
To retrieve a single resource of type Mono from endpoint /employee/{id}:
Mono<Employee> employeeMono = client.get()
.uri("/employees/{id}", "1")
.retrieve()
.bodyToMono(Employee.class);
employeeMono.subscribe(System.out::println);
6.2. Retrieving a Collection Resource
Similarly, to retrieve a collection resource of type Flux from endpoint /employees:
Flux<Employee> employeeFlux = client.get()
.uri("/employees")
.retrieve()
.bodyToFlux(Employee.class);
employeeFlux.subscribe(System.out::println);
We also have a detailed article on setting up and working with WebClient.
7. Spring WebFlux Security
We can use Spring Security to secure our reactive endpoints.
Letβs suppose we have a new endpoint in our EmployeeController. This endpoint updates Employee details and sends back the updated Employee.
Since this allows users to change existing employees, we want to restrict this endpoint to ADMIN role users only.
As a result, letβs add a new method to our EmployeeController:
@PostMapping("/update")
public Mono<Employee> updateEmployee(@RequestBody Employee employee) {
return employeeRepository.updateEmployee(employee);
}
Now, to restrict access to this method, letβs create SecurityConfig and define some path-based rules to allow only ADMIN users:
@EnableWebFluxSecurity
public class EmployeeWebSecurityConfig {
// ...
@Bean
public SecurityWebFilterChain springSecurityFilterChain(
ServerHttpSecurity http) {
http.csrf().disable()
.authorizeExchange()
.pathMatchers(HttpMethod.POST, "/employees/update").hasRole("ADMIN")
.pathMatchers("/**").permitAll()
.and()
.httpBasic();
return http.build();
}
}
This configuration will restrict access to the endpoint /employees/update. Therefore, only users with a role ADMIN will be able to access this endpoint and update an existing Employee.
Finally, the annotation @EnableWebFluxSecurity adds Spring Security WebFlux support with some default configurations.
For more information, we also have a detailed article on configuring and working with Spring WebFlux security.
8. Conclusion
In this article, we explored how to create and work with reactive web components as supported by the Spring WebFlux framework. As an example, we built a small Reactive REST application.
Then we learned how to use RestController and WebClient to publish and consume reactive streams.
We also looked into how to create a secured reactive endpoint with the help of Spring Security.
Other than Reactive RestController and WebClient, the WebFlux framework also supports reactive WebSocket and the corresponding WebSocketClient for socket style streaming of Reactive Streams.
For more information, we also have a detailed article focused on working with Reactive WebSocket with Spring 5.
