Category Archives: Spring

A Developer’s Guide to Testing Spring REST Clients with @RestClientTest

In modern microservices architecture, it’s rare for a service to live in complete isolation. Most applications need to communicate with other services over the network, typically via REST APIs. When you build a component that consumes an external REST API, a critical question arises: how do you test it reliably without actually making network calls to a live, and potentially unstable, external service?

This is where Spring Boot’s test slices come to the rescue. For testing your REST clients, the framework provides a powerful and elegant solution: the @RestClientTest annotation. Let’s dive deep into how you can use it to write clean, fast, and reliable tests for your HTTP client components.

What Exactly is @RestClientTest?

@RestClientTest is a “test slice” annotation specifically designed to test REST client components. Instead of loading your entire Spring application context (like @SpringBootTest does), it focuses only on the beans relevant to REST client operations. This makes your tests significantly faster and less prone to side effects from unrelated configurations.

When you use @RestClientTest, Spring Boot will auto-configure the following for you:

  • The Client Under Test: The specific REST client bean you want to test.
  • MockRestServiceServer: A bean that lets you mock the server-side responses. You can instruct it: “When my client calls /api/employees/1, respond with this specific JSON.”
  • RestTemplateBuilder: Used to help construct RestTemplate instances.
  • Jackson/Gson Support: It automatically includes support for serializing and deserializing JSON, so you can test your client-side data mapping.

In short, it provides the perfect, minimal environment to verify that your client builds the correct HTTP request and correctly parses the HTTP response — all without a single packet leaving your machine.

Continue reading A Developer’s Guide to Testing Spring REST Clients with @RestClientTest

Spring Security Context Propagation – Complete Guide

Spring Security’s SecurityContext is the cornerstone of authentication and authorization in Spring applications. It stores critical user details like authentication token, granted authorities, and principal information. However, when operations span multiple threads—common in asynchronous processing or reactive programming—propagating this context becomes a significant challenge. This guide explores various strategies to ensure your security context travels correctly across thread boundaries.


Understanding SecurityContext and ThreadLocal

At the heart of Spring Security lies the SecurityContextHolder, which uses a ThreadLocal strategy by default. This means each thread maintains its own isolated security context, which works perfectly in standard synchronous request-response cycles but breaks down when new threads are spawned.

The SecurityContextHolder supports three persistence strategies:

  • MODE_THREADLOCAL: Default strategy where context is bound to the current thread
  • MODE_INHERITABLETHREADLOCAL: Context is inherited by child threads created by the current thread
  • MODE_GLOBAL: Single context shared across all threads (rarely used in production)
Continue reading Spring Security Context Propagation – Complete Guide

Master Custom Authentication Providers in Spring Security 6

Spring Security is the de facto standard for securing Java applications, offering robust support for OAuth2, LDAP, and standard form logins. But what happens when “standard” isn’t enough?

You might face a scenario where user credentials live in a legacy mainframe, a proprietary API, or a multi-tenant database with complex sharding rules. In these cases, the default DaoAuthenticationProvider fails. Trying to hack standard filters to fit these requirements leads to brittle code, security vulnerabilities, and maintenance nightmares.

The solution lies in Spring Security’s modular architecture. By implementing a Custom Authentication Provider, you can inject your specific business logic directly into the security lifecycle without compromising the framework’s integrity.

In this guide, we will build a production-ready Custom Authentication Provider using Spring Boot 3 and Spring Security 6. We will cover the architecture, implementation details, configuration, and critical edge cases you must handle.


Understanding the Architecture

Before writing code, it is crucial to understand where your custom logic fits. Spring Security uses a delegation model.

  1. AuthenticationFilter: Intercepts the request.
  2. AuthenticationManager: The interface defining how authentication is processed.
  3. ProviderManager: The standard implementation that iterates through a list of providers.
  4. AuthenticationProvider: The component that actually validates the user.
Continue reading Master Custom Authentication Providers in Spring Security 6

Building Native Images of Spring Boot Applications with GraalVM: A Step-by-Step Guide

In the ever-evolving landscape of cloud-native development and serverless architectures, the demand for applications with lightning-fast startup times and minimal memory footprints is greater than ever. Java, traditionally known for its “write once, run anywhere” philosophy, has sometimes faced criticism regarding these very aspects. However, with the advent of GraalVM and Spring Boot’s dedicated support, Java is now a formidable contender in this space.

This post will guide you through the process of building GraalVM native images of your Spring Boot native applications (specifically Spring Boot 3.x), demonstrating how to unlock significant optimizations in startup time and memory consumption, perfect for serverless Java and general cloud native Java deployments.

Why Native Images? The GraalVM Advantage

Traditional Java applications run on the Java Virtual Machine (JVM). While the JVM offers incredible runtime optimizations through its Just-In-Time (JIT) compiler, there’s an inherent overhead: the JVM itself needs to start, classes need to be loaded, and code needs to be JIT-compiled at runtime.

GraalVM Native Image technology compiles your Java application ahead-of-time (AOT) into a standalone executable. This executable includes the application code, required libraries, and a minimal runtime environment (the Substrate VM) – all compiled into a single binary.

The benefits are substantial:

  • Blazing Fast Startup: Native images typically start in milliseconds, making them ideal for serverless functions, microservices, and environments where rapid scaling is crucial.
  • Reduced Memory Footprint: By eliminating the JVM overhead and only including the necessary code paths, native images use significantly less memory.
  • Smaller Deployment Size: The resulting binary is often much smaller than a traditional JAR file bundled with a JRE.
  • Lower Resource Consumption: Less CPU and memory usage translates to lower operational costs in cloud environments.

Spring Boot 3.x has embraced GraalVM native image compilation with first-class support, making the process more seamless than ever.

Continue reading Building Native Images of Spring Boot Applications with GraalVM: A Step-by-Step Guide

Securing Spring MVC with SiteMinder Pre‑Authentication – A Step‑by‑Step Guide

Enterprise Java applications frequently live behind a corporate Single Sign-On (SSO) gateway such as Broadcom (formerly CA) SiteMinder. SiteMinder authenticates users at the reverse-proxy layer — before any request ever reaches your application server — and then injects the verified identity into a well-known HTTP request header (typically SM_USER). Your Spring Boot application simply trusts that header and builds a security context from it, with no login form and no password handling of its own.

This pattern is called pre-authentication: the heavy lifting of credential verification is delegated to an external system, and your app only needs to map the already-authenticated identity to application-level roles. Spring Security has first-class support for this via RequestHeaderAuthenticationFilter and PreAuthenticatedAuthenticationProvider.

This tutorial walks through a complete Spring Boot 3.x / Spring Security 6.x configuration, covering Maven dependencies, the security filter chain using the modern lambda DSL, a UserDetailsService implementation, and tips for testing locally without a real SiteMinder agent.

Continue reading Securing Spring MVC with SiteMinder Pre‑Authentication – A Step‑by‑Step Guide

Leveraging Virtual Threads in Spring Boot 3.4+: Building High-Throughput Services

I’ve been shipping Java services for over a decade. I’ve tuned Tomcat thread pools, profiled connection leaks, and once reluctantly rewrote a critical service in WebFlux because blocking threads were killing us at scale. So when Java 21 landed with virtual threads baked in, I didn’t just read the JEP — I immediately threw it at a production-like load test.

The results were not subtle. This post is what I wish existed back then: an honest, methodical walkthrough of enabling virtual threads in Spring Boot 3.4, with real benchmark methodology, the gotchas that will actually bite you in production, and a clear-eyed take on when virtual threads won’t help at all.

Continue reading Leveraging Virtual Threads in Spring Boot 3.4+: Building High-Throughput Services

Spring Boot RestTemplate with Basic Auth: A Modern Guide

Communicating between microservices is a fundamental aspect of modern application development. Often, these services need to be secured. One of the simplest and most widely supported methods for securing REST APIs is Basic Authentication. In this guide, we’ll walk through how to configure and use Spring Boot’s RestTemplate to consume a REST API protected with Basic Auth.

We’ll cover the modern, recommended approach using Spring Security’s component-based configuration, updating older patterns you might find in other tutorials.

Project Setup

First, ensure your Spring Boot project includes the spring-boot-starter-web dependency. This starter conveniently bundles everything we need, including Spring MVC for creating the REST service, Tomcat as the embedded server, and RestTemplate support.

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

You’ll also need the spring-boot-starter-security dependency to enable security features.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Continue reading Spring Boot RestTemplate with Basic Auth: A Modern Guide