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
In this tutorial, weβll explore the main features of the Spring Cloud Gateway project, a new API based on Spring 6, Spring Boot 3 and Project Reactor.
The tool provides out-of-the-box routing mechanisms often used in microservices applications as a way of hiding multiple services behind a single facade.
For an explanation of the Gateway pattern without the Spring Cloud Gateway project, check out our previous article.
2. Routing Handler
Being focused on routing requests, the Spring Cloud Gateway forwards requests to a Gateway Handler Mapping, which determines what should be done with requests matching a specific route.
Letβs start with a quick example of how the Gateway Handler resolves route configurations by using RouteLocator:
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("r1", r -> r.host("**.baeldung.com")
.and()
.path("/baeldung")
.uri("http://baeldung.com"))
.route(r -> r.host("**.baeldung.com")
.and()
.path("/myOtherRouting")
.filters(f -> f.prefixPath("/myPrefix"))
.uri("http://othersite.com")
.id("myOtherID"))
.build();
}
Notice how we made use of the main building blocks of this API:
- Route β the primary API of the gateway. It is defined by a given identification (ID), a destination (URI) and set of predicates and filters.
- Predicate β a Java 8 Predicate β which is used for matching HTTP requests using headers, methods or parameters
- Filter β a standard Spring WebFilter
3. Dynamic Routing
Just like Zuul, Spring Cloud Gateway provides means for routing requests to different services.
The routing configuration can be created by using pure Java (RouteLocator, as shown in the example in Section 2) or by using properties configuration:
spring:
application:
name: gateway-service
cloud:
gateway:
routes:
- id: baeldung
uri: baeldung.com
- id: myOtherRouting
uri: localhost:9999
4. Routing Factories
Spring Cloud Gateway matches routes using the Spring WebFlux HandlerMapping infrastructure.
It also includes many built-in Route Predicate Factories. All these predicates match different attributes of the HTTP request. Multiple Route Predicate Factories can be combined via the logical βandβ.
Route matching can be applied both programmatically and via configuration properties file using a different type of Route Predicate Factories.
Our article Spring Cloud Gateway Routing Predicate Factories explores routing factories in more detail.
5. WebFilter Factories
Route filters make the modification of the incoming HTTP request or outgoing HTTP response possible.
Spring Cloud Gateway includes many built-in WebFilter Factories as well as the possibility to create custom filters.
Our article Spring Cloud Gateway WebFilter Factories explores WebFilter factories in more detail.
6. Spring Cloud DiscoveryClient Support
Spring Cloud Gateway can be easily integrated with Service Discovery and Registry libraries, such as Eureka Server and Consul:
@Configuration
@EnableDiscoveryClient
public class GatewayDiscoveryConfiguration {
@Bean
public DiscoveryClientRouteDefinitionLocator
discoveryClientRouteLocator(DiscoveryClient discoveryClient) {
return new DiscoveryClientRouteDefinitionLocator(discoveryClient);
}
}
6.1. LoadBalancerClient Filter
The LoadBalancerClientFilter looks for a URI in the exchange attribute property using ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.
If the URL has a lb scheme (e.g., lb://baeldung-service), itβll use the Spring Cloud LoadBalancerClient to resolve the name (i.e., baeldung-service) to an actual host and port.
The unmodified original URL is placed in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.
7. Monitoring
Spring Cloud Gateway makes use of the Actuator API, a well-known Spring Boot library that provides several out-of-the-box services for monitoring the application.
Once the Actuator API is installed and configured, the gateway monitoring features can be visualized by accessing /gateway/ endpoint.
8. Implementation
Weβll now create a simple example of the usage of Spring Cloud Gateway as a proxy server using the path predicate.
8.1. Dependencies
To add the project, weβll use the spring-cloud-starter-gateway dependency, which will fetch all the required dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>4.1.0</version>
</dependency>
8.2. Code Implementation
And now we create a simple routing configuration in the application.yml file:
spring:
cloud:
gateway:
routes:
- id: baeldung_route
uri: http://baeldung.com
predicates:
- Path=/baeldung/
management:
endpoints:
web:
exposure:
include: "*'
And hereβs the Gateway application code:
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
9. Conclusion
In this article, we explored some of the features and components that are part of Spring Cloud Gateway. This new API provides out-of-the-box tools for gateway and proxy support.
