Spring Boot Articles
A curated collection of articles covering Spring Boot from the basics to production operations, spanning beginner entry points to advanced design and operational topics.
-
How to Write Unit Tests for Controllers Using MockMvc in Spring Boot
A guide to writing Controller-specific tests that start the Spring context minimally with @WebMvcTest and verify HTTP requests and responses with MockMvc. Covers combining @MockBean with Mockito, JSON verification with jsonPath, and testing validation errors, with implementation examples.
-
How to Validate Spring Boot @ConfigurationProperties with Bean Validation - Detecting Errors at Startup and Testing
A step-by-step guide to combining @Validated and @NotNull/@Pattern with @ConfigurationProperties to instantly detect misconfiguration at application startup. Covers testing configuration validation with @SpringBootTest.
-
How to Standardize Error Responses with Problem Details (RFC 9457) in Spring Boot 3.x
Learn how to implement RFC-compliant error responses using the ProblemDetail class and ErrorResponse interface, leveraging the built-in Problem Details (RFC 9457) support introduced in Spring Boot 3.x. Includes migration steps from custom error response formats.
-
How to Configure Spring Boot as an OAuth2 Resource Server - Implementing JWT Validation and Scope-Based Authorization
A guide to validating JWTs issued by external IdPs such as Keycloak, Cognito, and Auth0 using Spring Security's resource server features, and implementing scope- and claim-based authorization.
-
Understanding Spring Boot Bean Lifecycle - How to Use @PostConstruct, @PreDestroy, and InitializingBean
A visual walkthrough of the Spring Bean lifecycle from creation through initialization to destruction, explaining how to choose between four implementation patterns — @PostConstruct, @PreDestroy, InitializingBean, and DisposableBean — based on your use case.
-
How to Encrypt Sensitive Information in Configuration Files Using Jasypt with Spring Boot
If you're concerned about storing database passwords and API keys in plain text in application.yml, Jasypt is an easy solution. This guide covers the full implementation process for production use, from encryption steps using the ENC() wrapper to integration with environment variables and CI.
-
How to Implement Declarative External API Calls with OpenFeign in Spring Boot
A comprehensive implementation guide covering everything from adding the spring-cloud-openfeign dependency and defining @FeignClient interfaces to error handling, timeout configuration, and logging settings. Aimed at developers frustrated by RestTemplate/WebClient boilerplate.
-
How to Use GraphQL with Spring Boot - Spring for GraphQL Basics and When to Use It vs REST API
Using Spring for GraphQL in Spring Boot 3.x, this guide covers schema definition, Query and Mutation Resolver implementation, handling N+1 problems with DataLoader, and integration with Spring Security. Includes a comparison with REST API to clarify when to choose GraphQL.
-
How to Use MongoDB with Spring Boot - From Spring Data MongoDB Basics to Queries and Aggregation
A step-by-step guide to integrating MongoDB into a Spring Boot application. A practical guide covering entity definition with @Document, CRUD operations with MongoRepository, query methods, custom queries with MongoTemplate, and Aggregation Pipeline — all through implementation code.
-
How to Automate Entity-DTO Mapping with MapStruct in Spring Boot
An implementation guide for auto-generating toDto()/toEntity() methods with MapStruct instead of writing them by hand. Covers adding dependencies, basic @Mapper usage, nested objects, custom conversions, and unit testing.
-
Spring Boot REST API Versioning Strategies - Choosing Between URL Path, Header, and Content-Type
Compare three REST API versioning approaches in Spring Boot (URI path, custom header, Accept header) with implementation code. Includes decision criteria for choosing the right strategy for your team's API characteristics and Swagger UI integration examples.
-
How to Test External API Calls with WireMock in Spring Boot
A practical guide to integrating WireMock into Spring Boot tests, defining external API stubs at the HTTP level for success cases, error cases, and timeouts. Also covers when to use Mockito vs WireMock.
-
How to Upload and Download Files to AWS S3 with Spring Boot
A guide to implementing file upload and download from a Spring Boot application to AWS S3. Covers how to choose between AWS SDK v2 and spring-cloud-aws 3.x, Service implementation with MultipartFile support, presigned URL generation, and IAM role authentication.
-
How to Implement Internationalization (i18n) in Spring Boot - Using MessageSource and LocaleResolver
A comprehensive guide to implementing internationalization in Spring Boot REST APIs using the Accept-Language header. Covers everything from configuring messages.properties and selecting a LocaleResolver, to localizing @Valid validation error messages and returning multilingual error responses with @RestControllerAdvice.
-
How to Output JSON Structured Logs in Spring Boot - Production-Ready Setup with Logstash Encoder and MDC
Step-by-step guide to configuring Spring Boot to output logs in JSON format using logstash-logback-encoder. Covers how to automatically attach request IDs and user IDs via MDC, Spring Boot 3.4 native structured logging support, and environment-based profile switching.
-
How to Achieve Graceful Shutdown and Zero-Downtime Deployment in Spring Boot
A practical guide to combining graceful shutdown configuration in Spring Boot 2.3+ with Kubernetes preStop hooks to ensure zero-downtime deployments without dropping in-flight requests.
-
Implementing CRUD REST API with Spring Boot - Basic Structure of Controller, Service, and Repository
A step-by-step guide to implementing CRUD (Create, Read, Update, Delete) REST API with Spring Boot. Build the three-layer architecture of Controller, Service, and Repository from scratch, and walk through setting up all four endpoints: GET, POST, PUT, and DELETE.
-
Implementing Kafka Producer and Consumer with Spring Boot
A hands-on guide to implementing Kafka Producer and Consumer from scratch in a Spring Boot application using spring-kafka. Covers the basics of KafkaTemplate and @KafkaListener, through to error handling, retries, and Dead Letter Topics, with a focus on code examples.
-
Spring Security Method Security - How to Implement RBAC with @PreAuthorize
Learn how to implement method-level Role-Based Access Control (RBAC) using @PreAuthorize/@PostAuthorize/@Secured in Spring Boot with practical code examples. Master fine-grained authorization control that cannot be achieved with SecurityFilterChain alone.
-
How to Implement Real-Time Communication with WebSocket in Spring Boot - Basics of STOMP and SockJS
Step-by-step guide to building a broadcast-style chat feature from scratch using Spring Boot + STOMP + SockJS. Covers @MessageMapping, SimpMessagingTemplate, and integration with Spring Security in a practical way.
-
How to Use Redis with Spring Boot - Implementation Patterns for Session Management, Caching, and Pub/Sub
Covers everything from basic RedisTemplate operations using spring-boot-starter-data-redis, to externalizing sessions with Spring Session, configuring Redis as a @Cacheable backend, and implementing Pub/Sub — organized by use case.
-
Spring Boot CORS Configuration: @CrossOrigin vs WebMvcConfigurer
Fix CORS errors in Spring Boot REST APIs. Covers three approaches — @CrossOrigin, WebMvcConfigurer, and SecurityFilterChain — with examples for React/Vue frontends and Spring Security integration.
-
How to Auto-Generate REST API Documentation Using OpenAPI (Swagger UI) with Spring Boot
A practical guide covering the introduction of springdoc-openapi, enhancing documentation with annotations, configuring Bearer token for JWT-authenticated endpoints, and YAML output.
-
How to Automatically Record Created and Updated Timestamps with JPA Auditing in Spring Boot
A guide to automatically recording entity creation and update timestamps using JPA Auditing in Spring Boot. Covers practical code for configuring @CreatedDate, @LastModifiedDate, @EnableJpaAuditing, and AuditorAware, including integration with Spring Security.
-
How to Implement RabbitMQ Producer and Consumer with Spring Boot - AMQP and spring-amqp Basics
A guide to defining RabbitMQ Exchange, Queue, and Binding in code using spring-amqp, and implementing message sending with RabbitTemplate and message receiving with @RabbitListener. Covers dead letter queues, retry configuration, and use case comparisons with Kafka.
-
Getting Started with Reactive Programming in Spring WebFlux - Differences from Spring MVC and When to Use Each
For Java developers familiar with Spring MVC, this article covers the non-blocking I/O mechanism of WebFlux, basic Mono/Flux operations, and endpoint implementation using RouterFunction. With a comparison table between Spring MVC and WebFlux and adoption criteria, you'll be able to decide whether to apply it to your own project.
-
How to Create Custom Validation Annotations in Spring Boot
Learn how to define reusable custom validation rules as annotations using @Constraint and ConstraintValidator, covering three implementation patterns including phone number format validation, duplicate email checking, and password confirmation.
-
Server-Side Rendering with Thymeleaf in Spring Boot: Implementation Guide
A hands-on tutorial covering how to integrate Thymeleaf into Spring Boot, including embedding model attributes in HTML, form processing, displaying Bean Validation errors, and Spring Security integration—all in one comprehensive guide.
-
How to Send Emails with JavaMailSender in Spring Boot - From Gmail/SMTP Configuration to HTML Emails
A zero-to-production guide on sending emails with JavaMailSender. Covers Gmail SMTP configuration, plain text and HTML emails, asynchronous sending with @Async, and troubleshooting common authentication errors — all with practical code examples.
-
How to Achieve Loose Coupling Between Modules with Spring Boot ApplicationEvent
Explains event-driven design using ApplicationEvent and ApplicationEventPublisher with implementation examples. Covers post-transaction processing with @TransactionalEventListener, asynchronous event handling, and testing.
-
How to Compile Natively with GraalVM Native Image in Spring Boot 3.x
A practical guide to natively compiling Spring Boot 3.x projects with GraalVM Native Image. Covers AOT processing mechanisms, adding Reflection hints, leveraging native-image-agent, runtime verification with Testcontainers, and troubleshooting.
-
Implementing Distributed Tracing with Micrometer Tracing and Zipkin in Spring Boot 3.2+
A practical guide to implementing distributed tracing using Micrometer Tracing and Zipkin in Spring Boot 3.2 and later. Covers migration from the deprecated Spring Cloud Sleuth, trace ID propagation between services, and verification via the Zipkin UI.
-
How to Deploy a Spring Boot Application to Kubernetes
A step-by-step guide to deploying a Dockerized Spring Boot application to Kubernetes. Covers creating Manifests for Deployment, Service, ConfigMap, and Secret, as well as configuring Actuator health endpoints as livenessProbe/readinessProbe — practical patterns you can use in production.
-
Spring Boot 2 to 3 Migration Guide: Step-by-Step Upgrade Checklist
Upgrade from Spring Boot 2.x to 3.x with this practical migration checklist. Covers javax to jakarta namespace changes, SecurityFilterChain migration, spring.factories deprecation, and fixes for common compilation and startup errors.
-
How to Implement a Circuit Breaker with Resilience4j in Spring Boot
A hands-on guide to implementing circuit breakers with Resilience4j and Spring Boot. Covers how to use @CircuitBreaker, @Retry, and @RateLimiter, fallback design, and parameter configuration via application.yml with practical code examples.
-
How to Implement Google Login (OAuth2) with Spring Boot
A step-by-step guide to implementing Google social login from scratch using Spring Security OAuth2 Client. Covers everything from how the OAuth2 authorization code flow works to application.yml configuration and UserInfo retrieval, while building an app that runs in a local environment.
-
Spring Boot Virtual Threads (Java 21): Setup, Performance, and Pitfalls
Enable virtual threads in Spring Boot 3.2+ with one setting. Covers performance benchmarks vs platform threads, ThreadLocal behavior changes, pinning issues, and @Async integration.
-
How to Implement File Upload and Download with REST API in Spring Boot - Using MultipartFile
Step-by-step guide to implementing file upload, storage, and download using MultipartFile. Covers size limit configuration, MIME type validation, exception handling, and production-ready code examples.
-
Visualizing Spring Boot Metrics with Prometheus and Grafana
A hands-on guide to collecting Spring Boot application metrics via Micrometer into Prometheus and visualizing them in real-time with a Grafana dashboard. Includes implementation examples for custom metrics (Counter and Gauge) and security considerations for production environments.
-
How to Speed Up Your Application with Spring Boot Cache - Using @Cacheable and @CacheEvict
An implementation guide for reducing DB access and improving response speed using Spring Cache Abstraction. Covers how to use @Cacheable, @CacheEvict, and @CachePut, selecting between Caffeine and Redis, and cache strategies with practical examples.
-
Differences Between Spring Boot Interceptors and Filters: Implementation Patterns for Pre/Post Request Processing
Explains the differences between Filter and HandlerInterceptor when implementing common processing such as request logging and authentication checks in Spring Boot. Illustrates differences in execution timing, Spring management, and accessible information with diagrams, and shows selection criteria by use case—authentication, logging, CORS, exception handling—with practical code examples.
-
Managing Database Migrations with Flyway in Spring Boot - From Version Control to Production
A practical guide to safely managing database schema changes using Flyway in Spring Boot applications. Covers initial setup, creating migration scripts, environment-specific application, and troubleshooting.
-
Spring Boot @Async Guide: Asynchronous Methods with @EnableAsync
Implement async processing in Spring Boot with @Async and @EnableAsync. Covers thread pool configuration, CompletableFuture, exception handling, and real-world patterns for background tasks.
-
How Spring Boot Auto-Configuration Works Under the Hood
Understand how Spring Boot auto-configuration works — from @EnableAutoConfiguration and @Conditional annotations to debugging and creating custom auto-configurations. A deep dive with practical examples.
-
How to Use Spring Boot Caching - Easy Performance Improvement with @Cacheable
A practical guide covering the Spring Cache Abstraction mechanism, how to use @Cacheable, @CacheEvict, and @CachePut, and how to switch to Caffeine or Redis — all with working code examples. Aimed at beginner-to-intermediate developers looking to easily reduce response latency caused by redundant calls to databases or external APIs.
-
How to Write Integration Tests in Spring Boot - Testing with @SpringBootTest and Testcontainers Including DB
A guide with code examples on how to write tests that start the entire application with @SpringBootTest, and how to implement integration tests that connect to a real DB on a Docker container using Testcontainers.
-
Spring Boot Logging with Logback and SLF4J: Configuration Guide
Configure logging in Spring Boot with Logback and SLF4J. Covers log levels, file output, logback-spring.xml, log rotation, and profile-based configuration with practical examples.
-
How to Call REST APIs in Spring Boot - When to Use RestTemplate vs WebClient
A practical guide to the two main approaches for calling external REST APIs in Spring Boot: RestTemplate and WebClient. Covers basic usage, criteria for choosing between them, timeout configuration, and error handling.
-
How to Run a Spring Boot App in a Docker Container - From Dockerfile Creation to Docker Compose Integration
A practical guide covering everything from Dockerfile optimization for Spring Boot apps (multi-stage builds and layer caching) to launching with PostgreSQL via Docker Compose, explaining the full journey from local development to production deployment.
-
Spring Boot JWT Authentication with Spring Security (Tutorial)
Build JWT authentication for a Spring Boot REST API from scratch. Covers token generation, validation, JwtAuthenticationFilter, and SecurityFilterChain configuration with complete code examples.
-
Understanding Transaction Management with @Transactional in Spring Boot - How to Use Propagation Levels and Isolation Levels
A comprehensive guide to transaction management using the @Transactional annotation in Spring Boot, from basics to practical usage. Covers default behavior, all 7 propagation levels, 4 isolation levels, and common failure patterns where rollback does not work (checked exceptions, self-invocation) with real examples.
-
Spring Security Authentication Tutorial: Basic Auth and Form Login
Step-by-step Spring Security authentication tutorial for Spring Boot. Covers Basic Auth, form login, UserDetailsService configuration, and common security pitfalls with working code.
-
How to Implement Pagination in Spring Boot REST API - Using Pageable and Page
Step-by-step guide to implementing REST API pagination using Spring Data JPA's Pageable and Page. Covers page specification via query parameters, sort conditions, custom response formats, and error handling with practical code examples.
-
Managing Configuration in Spring Boot with application.properties/yml - When to Use @Value vs ConfigurationProperties
A practical guide covering the basics of Spring Boot configuration file syntax, how to choose between @Value and @ConfigurationProperties in real-world projects, and managing settings with environment variables and placeholders.
-
Spring Data JPA Query Methods: Naming Conventions and Examples
Master Spring Data JPA query method naming conventions — findBy, existsBy, countBy, and more. Covers multiple conditions, sorting, pagination, and @Query with practical examples.
-
How to Map Entity Relationships with JPA in Spring Boot - Using @OneToMany and @ManyToOne
A beginner-friendly guide to correctly mapping relationships between entities (@OneToMany, @ManyToOne, @ManyToMany) with JPA in Spring Boot. Covers the differences between bidirectional and unidirectional associations, cascade configuration, choosing FetchType, and practical approaches to avoiding the N+1 problem and circular references.
-
Let's Write Tests in Spring Boot - Introduction to Unit Testing with JUnit and Mockito
A tutorial for those writing test code for Spring Boot applications for the first time. Step-by-step explanation of how to write unit tests for the Controller and Service layers using JUnit and Mockito, with @WebMvcTest and @MockBean.
-
How to Safely Switch Configurations per Environment Using Spring Boot Profiles
Using Spring Boot Profiles, you can switch configurations between development, staging, and production environments. This guide clearly explains how to write separate application.yml files, how to activate profiles, and common pitfalls to avoid.
-
How to Implement Group Validation and Method Validation with Spring Boot @Validated Annotation
A guide to safely integrating group validation and Service layer method validation using Spring Boot's @Validated, covering differences from @Valid and exception handling.
-
How to Simply Implement Validation with Spring Boot @Valid Annotation
A thorough explanation of how to use the @Valid annotation for validating form and API request data in Spring Boot, along with detailed control methods using various constraint annotations.
-
Introduction to Spring @Bean 'Names' - When Should You Set One? How Does It Work? What's the Priority?
When developing with Spring Boot, you often have opportunities to use @Bean. One thing that can be subtly tricky is the question of 'Should I give this @Bean a name, or just leave it alone?' This article organizes, from a practical perspective, what @Bean names are used for, when you should explicitly set one, and even 'which one gets chosen (priority)' when multiple Beans exist.
-
What is @Configuration / @Bean in Spring Boot? A Clear Guide to How to Use Them
Have you ever come across @Configuration or @Bean while developing with Spring Boot? These are points that tend to cause confusion, such as 'What's the difference from @Component?' and 'Where is the correct place to use them?' This article explains the roles and usage of @Configuration/@Bean with concrete examples.
-
Getting Started with Spring Boot Actuator
A beginner-friendly guide to quickly exposing health checks and metrics with Spring Boot Actuator, and building the monitoring foundation needed for operations.
-
How to Return Unified Error Responses in Spring Boot REST API - Using @ControllerAdvice and @ExceptionHandler
Explains how to implement unified JSON error responses for exceptions in Spring Boot REST API. Introduces design patterns and code examples for returning validation errors, business errors, and system errors with appropriate HTTP status codes using @ControllerAdvice and @ExceptionHandler.
-
Spring Boot @Scheduled: Cron Jobs, fixedRate, and fixedDelay Explained
Learn how to schedule tasks in Spring Boot using @Scheduled. Covers cron expressions, fixedRate vs fixedDelay, timezone settings, and how to avoid common pitfalls like duplicate execution and silent failures.
-
What is @Component in Spring Boot? Differences from @Bean Explained
A beginner-friendly explanation of @Component in Spring Boot. Covers the differences from @Bean, when to use each, the relationship with dependency injection, and common decision points in real-world development, with code examples.
-
What is Spring Boot Starter?
A beginner-friendly explanation of the role and mechanism of Spring Boot Starters. Covers how to choose key Starters like spring-boot-starter-web, why dependency management becomes easier, and common pitfalls to watch out for.
-
Spring AOP Guide: Aspect-Oriented Programming in Spring Boot
Learn how Spring AOP works and how to use it for logging, security, and other cross-cutting concerns. Includes setup instructions and practical code examples for Spring Boot.
-
Spring Boot Dependency Injection Explained with Examples
Learn how Dependency Injection (DI) works in Spring Boot. Covers constructor injection, @Autowired, and the benefits of DI for testable, maintainable code — with practical examples.
-
Spring vs Spring Boot: Key Differences Explained
What's the difference between Spring and Spring Boot? This guide compares configuration, dependency management, and startup to help you understand when to use each — with practical examples.
-
Why Is Spring Boot Commonly Used in Business System Development?
Explains why Spring Boot is chosen for business systems from the perspectives of development speed, maintainability, and operability. Covers which projects it suits and which it doesn't, along with pre-adoption checkpoints from a practical standpoint.