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
With Spring Boot 2 and the new non-blocking server Netty, we donβt have the Servlet context API anymore, so letβs discuss the way how we can express different kind of HTTP status codes, using the new stack.
2. Semantic Response Status
Follow standard RESTful practice, we naturally need to make use of the full range of HTTP status codes to express the semantics of the API properly.
2.1. Default Return Status
Of course, when everything goes well, the default response status is the 200 (OK):
@GetMapping(
value = "/ok",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public Flux<String> ok() {
return Flux.just("ok");
}
2.2. Using Annotations
We can alter the default return status adding the @ResponseStatus annotation to the method:
@GetMapping(
value = "/no-content",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
@ResponseStatus(HttpStatus.NO_CONTENT)
public Flux<String> noContent() {
return Flux.empty();
}
2.3. Changing the Status Programmatically
In some cases, depending on our serverβs behavior, we could decide to change the returned status programmatically instead of a prefixed returned status used by default or with annotations.
We can achieve that injecting ServerHttpResponse in our method directly:
@GetMapping(
value = "/accepted",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public Flux<String> accepted(ServerHttpResponse response) {
response.setStatusCode(HttpStatus.ACCEPTED);
return Flux.just("accepted");
}
Now we can choose which HTTP status code we return right in the implementation.
2.4. Throwing an Exception
Any time we throw an exception, the default HTTP return status is omitted and Spring tries to find an exception handler to deal with it:
@GetMapping(
value = "/bad-request"
)
public Mono<String> badRequest() {
return Mono.error(new IllegalArgumentException());
}
@ResponseStatus(
value = HttpStatus.BAD_REQUEST,
reason = "Illegal arguments")
@ExceptionHandler(IllegalArgumentException.class)
public void illegalArgumentHandler() {
//
}
To learn more about how to do that, definitely check-out the Error Handling article on Baeldung.
2.5. With ResponseEntity
Letβs now have a quick look at an interesting alternative β the ResponseEntity class.
This allows us to choose which HTTP status we want to return and also to customize our responses much further, using a very useful fluent API:
@GetMapping(
value = "/unauthorized"
)
public ResponseEntity<Mono<String>> unathorized() {
return ResponseEntity
.status(HttpStatus.UNAUTHORIZED)
.header("X-Reason", "user-invalid")
.body(Mono.just("unauthorized"));
}
2.6. With Functionals Endpoints
With Spring 5, we can define endpoints in a functional way, so, we can change the default HTTP status programmatically as well:
@Bean
public RouterFunction<ServerResponse> notFound() {
return RouterFunctions
.route(GET("/statuses/not-found"),
request -> ServerResponse.notFound().build());
}
3. Conclusion
When implementing an HTTP API, the framework gives a number of options to intelligently deal with the status codes weβre exposing back to the client.
This article should be a good starting point to explore these and understand how you can roll out expressive, friendly API, with clean, RESTful semantics.
