Skip to main content

Spring

JUnit 6 with Spring Boot: Unit, Slice, and Integration Testing

A complete guide to testing Spring Boot applications with JUnit 6. Covers unit tests with plain JUnit, slice tests (@WebMvcTest, @DataJpaTest, @JsonTest), full integration tests with @SpringBootTest, context caching, Testcontainers, and best practices for each layer.

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.

Log4j2 Logging Levels – Complete Guide

Imagine your application's log file as a constant stream of information. In a production crisis, this stream becomes a firehose. How do you find the single critical error message in a flood of routine status updates? The answer lies in logging levels. These aren't just labels; they are the fundamental control mechanism in Log4j2. They allow developers to filter noise, pinpoint failures, and monitor application health effectively. Mastering this hierarchy is the key to creating logs that are helpful, not overwhelming. This guide explores Log4j2’s levels, from configuration to real-world best practices. The Logging Threshold: How Levels Work Think of logging levels as a gatekeeper's volume knob. Each log message you write (an "event") is assigned a level of importance, or severity. The logger itself is then configured with a threshold level. When a message arrives, the framework compares its severity to the logger's threshold. Only messages at or above the configured threshold are processed and sent to their destination (like a file or the console). This simple mechanism provides fine-grained control over your application's verbosity. You can run the exact same code in different environments and get drastically different log outputs—all without changing a single line of Java. In development, you might set the threshold low to see everything. In production, you set it high to capture only significant errors.

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.

Solved: Bean property ‘configurationClass’ is not writable or has an invalid setter method

Every developer has those moments where a seemingly simple task turns into a head-scratching puzzle. This error, encountered while trying to configure a custom LocalSessionFactoryBean in Spring Boot, is a perfect example of a subtle type mismatch causing a cryptic failure. The Scenario and the Error The goal was to set up a custom SessionFactory bean using Spring's LocalSessionFactoryBean. The initial, problematic configuration was: @Configuration public class HibernateConfig { @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); // … set data source, hibernate properties … // This line caused the error! sessionFactory.setConfigurationClass(org.hibernate.cfg.Configuration.class); return sessionFactory; } } This configuration resulted in the following exception upon application startup: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Bean property 'configurationClass' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

Don’t Specify Version Numbers in Spring XML Schema References

If you’ve been working with Spring Framework for a while, especially with its XML-based configuration, you’ve likely encountered a pattern in the <beans> element where schema locations are defined. It often looks something like this: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Your bean definitions here --> </beans> Notice the -3.0.xsd at the end of the schema locations? This explicitly ties your configuration to a specific version of the Spring schema. While this might seem harmless or even like a good idea for precision, it can actually lead to unnecessary headaches and maintenance overhead. Why You Shouldn’t Include Version Numbers The Spring Framework is designed with backward compatibility in mind. When a new version of Spring is released (e.g., Spring 3.0, 4.0, 5.0, etc.), the XML schemas are generally updated to include new features or deprecate old ones, but they usually remain compatible with configurations written for previous versions, especially if you’re not using any of the very latest, specific features.

Configuring ResourceBundleViewResolver in Spring MVC

In a Spring MVC application, a ViewResolver is responsible for mapping logical view names that your controllers return to actual .jsp files (or Thymeleaf templates, etc.). When you need to support multiple locales and provide messages or titles that vary per language, a ResourceBundleViewResolver is a convenient choice. This post walks through a minimal, but complete, configuration that you can drop into any Spring MVC project. Problem Statement Suppose you want a home.jsp that displays a greeting, a welcome message, and a page title, all of which should change depending on the user’s locale. You also want to keep the JSPs simple, so you delegate the translation of these messages to a standard Java ResourceBundle (properties file). Solution Overview Define the view resolver so it first looks for a messages_*.properties file. Configure the ViewResolver hierarchy to fall back to the default view resolver if a match isn’t found. Create a simple controller that forwards to a logical view name. Write the JSP that pulls values from the resource bundle.

A Practical Guide to Monitoring Spring Boot Microservices with Prometheus & Grafana

Microservices are powerful. They allow us to build scalable, resilient, and independently deployable systems. But this power comes with a cost: complexity. When you have dozens or even hundreds of services interacting, figuring out what’s going on—especially when something goes wrong—can feel like searching for a needle in a haystack of haystacks. This is where observability comes in. It’s more than just “monitoring”; it’s about gaining deep, actionable insights into your system’s behavior. We can break observability down into three pillars: Logs: Structured, event-based records of what happened. “User X failed to log in at 10:05 PM.” Metrics: Aggregated, numerical data over time. “The average API response time over the last 5 minutes was 200ms.” Traces: The end-to-end journey of a request as it travels through multiple services. “Request ABC started at the API gateway, went to the user-service, then the auth-service, and took 350ms in total.” In this guide, we’ll focus on the cornerstone of observability: metrics. We’ll build a complete, production-grade monitoring stack for a Spring Boot microservice using an industry-standard toolkit. The Monitoring Dream Team We’ll use a combination of powerful tools that work seamlessly together: Spring Boot Actuator: Provides production-ready features for our app, including a wealth of internal metrics out-of-the-box. Micrometer: An application metrics facade that acts as a universal translator. Spring Boot uses it to format its metrics so that various monitoring systems can understand them. We’ll configure it to talk “Prometheus”. Prometheus: The powerhouse of our stack. It’s a time-series database that periodically “scrapes” (pulls) metrics from our application and stores them efficiently. Grafana: The visualization layer. Grafana connects to Prometheus, queries the stored metrics, and turns them into beautiful, insightful dashboards. Here’s the data flow we’re building: Spring Boot App → Actuator → Micrometer → a /prometheus endpoint → Prometheus Scraper → Grafana Dashboard Let’s get building!

Sending Emails in Spring Boot 3: A Complete Guide

Email isn't just for newsletters; it's the backbone of modern application workflows. From sending critical account verification links to delivering daily reports, a reliable email system is non-negotiable. Luckily, Spring Boot makes sending emails clean, configurable, and production-ready with its powerful JavaMailSender interface. In this comprehensive guide, we'll walk you through everything you need to know to become an email pro with Spring Boot 3. We'll cover sending plain text and rich HTML emails, handling attachments, and supercharging your system with asynchronous processing for blazing-fast performance. Let's get started. 1. Setting the Stage: Project Setup First things first, we need to tell our Spring Boot project that we intend to use its mail-sending capabilities. We do this by adding a single dependency to our pom.xml file.

Spring Cloud: Getting started with Hystrix Dashboard

⚠️ This tutorial is outdated. Hystrix Dashboard was removed from Spring Cloud and does not work with Spring Boot 3.x. The modern approach is Resilience4j metrics with Prometheus & Grafana — see the Spring Cloud Netflix migration guide. This post remains online for teams maintaining legacy systems. This is a quick tutorial on Hystrix dashboard. Hystrix dashboard allows you to view the overall status of your Spring cloud application at a single glance. It provides access to vital metrics of your application and gives you a graphical representation of those for better understanding. This post is the continuation of Spring Cloud: Adding Hystrix Circuit Breaker and Spring Cloud: Playing with Hystrix Circuit Breaker. Please go through those post, if you haven't. Those posts explain about Hystrix circuit breaker. TL;DR You can download whole project by clicking following link. Spring Cloud (V2.3.1) Hystrix DashboardDownload