A comprehensive, hands-on Spring Boot 4 playground that explores and demonstrates modern Java practices β from declarative HTTP clients and API versioning strategies to null-safety, observability, Spring AI, and AOT optimizations.
- Overview
- Repository Structure
- Modules
- HTTP Interfaces Demo
- API Versioning
- Null Safety with JSpecify & NullAway
- OpenTelemetry Observability
- REST Client Error Handling
- REST Test Client
- REST vs MockMvc Testing
- Jackson 3 JSON Mapping
- JMS Messaging
- Dynamic Bean Registration
- Spring AI 2 Demo
- Spring Data AOT
- Spring Native Resilience
- Spring Security MFA
- Technologies Used
- Prerequisites
- Getting Started
- Running Individual Modules
- Key Spring Boot 4 Features Showcased
- Author
This repository serves as a learning playground and reference implementation for Spring Boot 4 capabilities. Each sub-module is a self-contained Spring Boot application that focuses on a specific feature, pattern, or best practice introduced or improved in the Spring Boot 4 / Spring Framework 7 ecosystem.
Whether you're a beginner exploring Spring Boot 4 for the first time, or an experienced developer looking for a reference implementation of cutting-edge features, this playground has something for you.
- π¬ 19+ focused modules β each module demonstrates one concept cleanly
- ποΈ Real-world patterns β not toy examples, but production-ready approaches
- π Modern Java practices β leverages Java 21+ features throughout
- π¦ Self-contained β each module runs independently
- π§ͺ Test-driven β testing strategies are first-class citizens
Spring-Boot-4-Playground/
β
βββ api-versioning-demo/ # URI path segment versioning
βββ api-versioning-header/ # HTTP header-based versioning
βββ api-versioning-media-type-param/ # Media type parameter versioning
βββ api-versioning-path-segment/ # Path segment versioning strategy
βββ api-versioning-query-param/ # Query parameter versioning
β
βββ dynamic-bean-registration/ # Runtime bean registration
βββ http-interfaces-demo/ # Declarative HTTP clients
βββ jackson3-json-mapping/ # Jackson 3 new features
βββ messaging-jms/ # JMS messaging with Spring
βββ null-safety-jspecify-nullaway/ # Compile-time null safety
βββ opentelemetry-demo/ # Distributed tracing & metrics
βββ rest-client-error-handling/ # Robust error handling patterns
βββ rest-test-client/ # RestTestClient usage
βββ rest-vs-mock-web-testing/ # Testing strategy comparison
βββ spring-ai-2-demo/ # Spring AI 2.x integration
βββ spring-data-aot/ # Spring Data with AOT optimizations
βββ spring-native-resilience/ # Native image + resilience patterns
βββ spring-security-mfa/ # Multi-Factor Authentication
Path: http-interfaces-demo/
Demonstrates Spring Boot 4's declarative HTTP client support using the @HttpExchange annotation family. This is the Spring-native alternative to Feign clients β no third-party dependencies required.
Key concepts:
@HttpExchange,@GetExchange,@PostExchange,@PutExchange,@DeleteExchange- Registering HTTP interface proxies with
HttpServiceProxyFactory - Integration with
RestClientandWebClientbackends - Error handling in declarative clients
Example:
@HttpExchange("/users")
public interface UserClient {
@GetExchange("/{id}")
UserDto getUser(@PathVariable Long id);
@PostExchange
UserDto createUser(@RequestBody UserDto user);
}Paths: api-versioning-demo/, api-versioning-header/, api-versioning-media-type-param/, api-versioning-path-segment/, api-versioning-query-param/
A comprehensive exploration of 5 different API versioning strategies in Spring Boot 4. Each module implements the same API with a different versioning approach, allowing direct comparison.
| Module | Strategy | Example |
|---|---|---|
api-versioning-path-segment |
URI Path | /api/v1/users vs /api/v2/users |
api-versioning-query-param |
Query Parameter | /api/users?version=1 |
api-versioning-header |
Custom Header | X-API-Version: 2 |
api-versioning-media-type-param |
Accept Header | Accept: application/vnd.app.v2+json |
api-versioning-demo |
Combined Demo | Showcases all strategies |
When to use which strategy:
- π£οΈ Path versioning β most visible, great for public APIs
- π Query param β easy to test in browser, less RESTful
- π¨ Header versioning β clean URLs, used by GitHub API
- π Media type β most RESTful, preferred by purists
Path: null-safety-jspecify-nullaway/
Demonstrates compile-time null safety using JSpecify annotations and NullAway β a fast Checker Framework alternative that plugs into the Java compiler via Error Prone.
Key concepts:
@Nullableand@NonNullannotations from JSpecify- Configuring NullAway with the Error Prone compiler plugin
- Null-safe service and controller layers
- Eliminating
NullPointerExceptions at compile time
Maven configuration:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-XDcompilePolicy=simple</arg>
<arg>-Xplugin:ErrorProne -XepOpt:NullAway:AnnotatedPackages=com.example</arg>
</compilerArgs>
</configuration>
</plugin>π‘ Spring Boot 4 / Spring Framework 7 now ships with JSpecify null-safety annotations natively across the framework codebase.
Path: opentelemetry-demo/
Showcases full observability with the new spring-boot-starter-opentelemetry that ships in Spring Boot 4 β covering distributed tracing, metrics, and log correlation out of the box via OTLP.
Key concepts:
- Auto-configuration of the OpenTelemetry SDK
- Exporting traces and metrics over OTLP (gRPC/HTTP)
- Automatic instrumentation of Spring MVC, WebClient, JDBC
- Trace context propagation across service boundaries
- Integration with Jaeger / Zipkin / Grafana
Configuration example:
management:
otlp:
tracing:
endpoint: http://localhost:4318/v1/traces
tracing:
sampling:
probability: 1.0Path: rest-client-error-handling/
A deep-dive into robust error handling strategies with Spring Boot 4's RestClient β the modern, synchronous successor to RestTemplate.
Key concepts:
- Custom
ResponseErrorHandlerimplementations onStatus()error mapping chains- Translating HTTP errors into domain exceptions
- Retry strategies for transient failures
- Logging and auditing failed requests
Example:
RestClient.builder()
.baseUrl("https://api.example.com")
.defaultStatusHandler(HttpStatusCode::is4xxClientError,
(req, res) -> { throw new ClientException(res.getStatusCode()); })
.defaultStatusHandler(HttpStatusCode::is5xxServerError,
(req, res) -> { throw new ServerException("Upstream failure"); })
.build();Path: rest-test-client/
Demonstrates the new RestTestClient introduced in Spring Boot 4 β a test-focused HTTP client that can operate against both MockMvc (no server needed) and a real running server.
Key concepts:
@AutoConfigureMockMvc+RestTestClientinjection- Fluent assertion API for response validation
- JSON path assertions
- Testing both controller slices and full integration
Example:
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
RestTestClient restTestClient;
@Test
void shouldReturnUser() {
restTestClient.get().uri("/api/users/1")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.name").isEqualTo("Omar");
}
}Path: rest-vs-mock-web-testing/
A side-by-side comparison of different testing strategies in Spring Boot 4:
| Approach | Speed | Scope | Use Case |
|---|---|---|---|
MockMvc |
β‘ Fastest | Controller layer | Unit & slice tests |
RestTestClient (MockMvc) |
β‘ Fast | Controller layer | Fluent API preference |
RestTestClient (Real server) |
π’ Slower | Full stack | Integration tests |
TestRestTemplate |
π’ Slower | Full stack | Legacy integration |
Key concepts:
- When to use
@WebMvcTestvs@SpringBootTest - Trade-offs between speed and fidelity
- Structuring test suites for maximum coverage
Path: jackson3-json-mapping/
Explores the Jackson 3.x changes that come with Spring Boot 4, including new annotation behavior, improved Records support, and updated serialization defaults.
Key concepts:
- Jackson 3 migration from Jackson 2
@JsonViewand@JsonPropertychanges- Serialization of Java Records
- Custom serializers and deserializers
- Property naming strategies
Path: messaging-jms/
Demonstrates JMS (Java Message Service) messaging patterns with Spring Boot 4, covering both point-to-point queues and publish-subscribe topics.
Key concepts:
- Configuring
JmsTemplatefor sending messages @JmsListenerfor consuming messages- Message converters (JSON, Object)
- Transaction management with JMS
- Error handling and Dead Letter Queues (DLQ)
- Integration with ActiveMQ Artemis
Example:
@Component
public class OrderProducer {
@Autowired
private JmsTemplate jmsTemplate;
public void sendOrder(Order order) {
jmsTemplate.convertAndSend("orders.queue", order);
}
}
@Component
public class OrderConsumer {
@JmsListener(destination = "orders.queue")
public void processOrder(Order order) {
// process the order
}
}Path: dynamic-bean-registration/
Demonstrates runtime bean registration in Spring Boot 4 using the new BeanDefinitionRegistrar APIs and programmatic context customization.
Key concepts:
BeanDefinitionRegistryPostProcessorfor dynamic registration- Condition-based bean creation at runtime
- Plugin-style architecture with dynamic discovery
- Using
DefaultListableBeanFactoryfor programmatic registration
Path: spring-ai-2-demo/
An introduction to Spring AI 2.x β the official Spring framework for integrating AI/ML capabilities into Spring applications, including LLM chat completions, embeddings, and prompt engineering.
Key concepts:
ChatClientfor LLM interactions- Prompt templates and
PromptTemplate - Streaming responses with
Flux<String> - Embedding models for vector search
- Integration with OpenAI, Anthropic, Ollama, and other providers
- Retry and observability for AI calls
Example:
@Service
public class AiService {
private final ChatClient chatClient;
public String ask(String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
}π Requires an AI provider API key (e.g.,
OPENAI_API_KEY).
Path: spring-data-aot/
Explores Ahead-of-Time (AOT) optimizations for Spring Data in Spring Boot 4, enabling dramatically faster startup times and lower memory footprint β particularly useful for serverless and containerized deployments.
Key concepts:
- AOT processing with
spring-data-aotprocessor - Repository proxy generation at build time
- GraalVM Native Image compatibility
- AOT hints for reflection-heavy components
- Build-time validation of repository queries
Benefits:
- β‘ Faster application startup (no proxy creation at runtime)
- πΎ Lower memory usage
- π Build-time detection of invalid queries
Path: spring-native-resilience/
Combines GraalVM Native Image compilation with resilience patterns (circuit breakers, retries, rate limiters) to build ultra-fast, fault-tolerant microservices.
Key concepts:
- Resilience4j integration with Spring Boot 4
@CircuitBreaker,@Retry,@RateLimiter,@Bulkheadannotations- Native image compilation with Spring AOT
- Custom AOT hints for Resilience4j
- Health indicators for circuit breaker state
Example:
@Service
public class ExternalService {
@CircuitBreaker(name = "externalAPI", fallbackMethod = "fallback")
@Retry(name = "externalAPI")
public String callExternal() {
return externalClient.getData();
}
public String fallback(Exception ex) {
return "Fallback response";
}
}Path: spring-security-mfa/
Implements Multi-Factor Authentication (MFA) using Spring Security 7 with TOTP (Time-based One-Time Password) support β the same standard used by Google Authenticator and Authy.
Key concepts:
- TOTP-based MFA with
google-authenticator/JJWT - Custom
AuthenticationProviderfor MFA verification - QR code generation for authenticator app setup
- MFA enrollment flow (register β scan β verify)
- Remember-device functionality
- Spring Security filter chain customization
Authentication flow:
1. User submits username + password
2. System validates credentials β
3. System prompts for TOTP code π±
4. User enters 6-digit code from authenticator app
5. System validates TOTP β
6. Access granted π
| Category | Technology | Version |
|---|---|---|
| β Language | Java | 21+ |
| π± Framework | Spring Boot | 4.x |
| πΏ Core | Spring Framework | 7.x |
| π Security | Spring Security | 7.x |
| π€ AI | Spring AI | 2.x |
| π Observability | OpenTelemetry | Latest |
| π‘οΈ Null Safety | JSpecify + NullAway | Latest |
| π¦ Build | Apache Maven | 3.9+ |
| ποΈ JSON | Jackson | 3.x |
| π¨ Messaging | Spring JMS / ActiveMQ Artemis | Latest |
| π Resilience | Resilience4j | Latest |
| π§ͺ Testing | JUnit 5, MockMvc, RestTestClient | Latest |
Before running any module, ensure you have the following installed:
- β Java 21+ β Download OpenJDK
- π¦ Maven 3.9+ β Download Maven
- π³ Docker (optional, for external services like Jaeger, ActiveMQ) β Download Docker
- π API Keys (for
spring-ai-2-demo) β e.g., OpenAI API Key
Verify your setup:
java -version # Should show 21+
mvn -version # Should show 3.9+
docker --version # Optionalgit clone https://github.com/drissiOmar98/Spring-Boot-4-Playground.git
cd Spring-Boot-4-Playgroundmvn clean install -DskipTestscd http-interfaces-demo
mvn clean installEach module is a standalone Spring Boot application. Navigate to the module directory and run:
# Navigate to any module
cd <module-name>
# Run with Maven
mvn spring-boot:run
# Or build and run the JAR
mvn clean package -DskipTests
java -jar target/*.jarcd spring-ai-2-demo
export OPENAI_API_KEY=your_api_key_here
mvn spring-boot:run# Start Jaeger for trace visualization
docker run -d --name jaeger \
-p 16686:16686 \
-p 4318:4318 \
jaegertracing/all-in-one:latest
cd opentelemetry-demo
mvn spring-boot:run
# View traces at http://localhost:16686# Start ActiveMQ Artemis
docker run -d --name artemis \
-p 8161:8161 \
-p 61616:61616 \
apache/activemq-artemis:latest
cd messaging-jms
mvn spring-boot:runcd spring-security-mfa
mvn spring-boot:run
# Access at http://localhost:8080This playground highlights the major improvements and new features in Spring Boot 4:
Auto-configures the OpenTelemetry SDK for traces and metrics over OTLP β demonstrated in opentelemetry-demo.
Spring Boot 4 adds auto-configuration for @HttpExchange interface clients, making declarative HTTP clients even simpler β demonstrated in http-interfaces-demo.
The new test-focused HTTP client that works with both MockMvc and real servers β demonstrated in rest-test-client and rest-vs-mock-web-testing.
Spring Framework 7 adopts JSpecify annotations across the codebase, enabling null-safe programming by default β demonstrated in null-safety-jspecify-nullaway.
Improved build-time processing for faster startup and GraalVM compatibility β demonstrated in spring-data-aot and spring-native-resilience.
Spring Boot 4 migrates to Jackson 3, with updated serialization behavior and better Records support β demonstrated in jackson3-json-mapping.
Omar Drissi
π GitHub β’
πΌ LinkedIn
β If you find this project useful, please give it a star! β
It helps others discover the project and motivates further development.
Made with β€οΈ and β using Spring Boot 4