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.
-
@MockBean Deprecated in Spring Boot 3.4 - Migrating to @MockitoBean and @MockitoSpyBean and How to Use Them
@MockBean/@SpyBean are deprecated in Spring Boot 3.4. This guide explains the correct imports for their replacements @MockitoBean and @MockitoSpyBean, the package relocation, differences from the old API, and step-by-step procedures for migrating existing tests in bulk, with practical examples.
-
How to Automatically Record Change History (Audit Logs) with Spring Boot + Hibernate Envers
A guide to implementing automatic recording of the full revision history of "who changed what, when, and how" in Spring Boot using Hibernate Envers. Covers _AUD table generation with @Audited, retrieving past versions with AuditReader, attaching user information to revisions, and strategies to prevent history table bloat.
-
How to Build an API Gateway with Spring Cloud Gateway - Routing, Filters, and Rate Limiting
A practical guide to building an API Gateway that sits in front of microservices with Spring Cloud Gateway. This hands-on tutorial covers route definitions, path rewriting, authentication and logging with GlobalFilter, RequestRateLimiter with Redis integration, and fallback integration with Resilience4j.
-
How to Export and Import CSV in Spring Boot - Handling Character Encoding, Large Datasets, and Validation with OpenCSV
A practical guide to implementing CSV download/upload with Spring Boot and OpenCSV. Covers Shift_JIS/UTF-8+BOM support to prevent garbled text in Excel, memory-efficient output of large datasets with StreamingResponseBody, mapping with @CsvBindByName, and row-level validation with error-row return on import, all explained with code.
-
How to Create Your Own Custom Starter in Spring Boot - AutoConfiguration and Metadata Setup
A guide to promoting shared internal logging configuration and external API integration Beans into a custom Starter that activates simply by adding a dependency. From splitting the autoconfigure and starter modules, @AutoConfiguration, AutoConfiguration.imports registration, conditional configuration with @ConditionalOn, to @ConfigurationProperties and generating configuration metadata JSON, we build everything end-to-end in a hands-on manner.
-
How to Fix LazyInitializationException in Spring Boot + JPA - Causes and Solutions for "could not initialize proxy - no Session"
Solve the LazyInitializationException (could not initialize proxy - no Session) that crashes the moment you access a lazily-loaded association in Spring Data JPA, working backwards from how Hibernate sessions and transaction boundaries operate. Compares the four proper approaches—JOIN FETCH, @EntityGraph, DTO projection, and @Transactional—and provides criteria for making decisions without resorting to open-in-view=true or switching to EAGER.
-
How to Create Custom Health Checks (HealthIndicator) and Custom Actuator Endpoints in Spring Boot
Learn how to integrate the health status of dependencies such as external APIs, databases, and message brokers into your custom health using a custom HealthIndicator, assign them to readiness/liveness via health groups, and add custom operational Actuator endpoints with @Endpoint. Includes verification with curl.
-
How to Receive Request Parameters in Spring Boot - Choosing Between @RequestParam, @PathVariable, @RequestBody, and @ModelAttribute
A guide to the four annotations for receiving client input in Spring Boot Controllers—@RequestParam, @PathVariable, @RequestBody, and @ModelAttribute—with criteria for choosing between them based on the input source: query strings, path variables, JSON bodies, and forms. Covers required/defaultValue, multiple values with List, and the 400 behavior on type conversion failures with implementation examples.
-
How to Retrieve DTOs Directly with Spring Data JPA Projections - Choosing Between Interface-Based and Class-Based Projections
Learn how to SELECT only the columns you need and project them directly into DTOs/interfaces with Spring Data JPA projections. Compares interface-based, class-based (constructor), and dynamic projections through implementations, covering differences in the generated SQL, selection criteria, and pitfalls when combined with @Query.
-
How to Run Startup Logic with CommandLineRunner and ApplicationRunner in Spring Boot
A guide to using CommandLineRunner and ApplicationRunner to run logic exactly once right after a Spring Boot application finishes starting. Covers minimal implementations, execution order with @Order, receiving startup arguments via ApplicationArguments, behavior on exceptions, and how to choose between @PostConstruct and ApplicationReadyEvent, all with practical examples.
-
How to Execute Raw SQL with Spring Boot's JdbcTemplate - Using queryForObject, RowMapper, and Batch Updates
A hands-on, code-focused guide to safely writing raw SQL with Spring's standard JdbcTemplate, covering single-row and scalar retrieval with queryForObject, multi-row retrieval with RowMapper/BeanPropertyRowMapper, CRUD with update/batchUpdate, named parameter binding with NamedParameterJdbcTemplate, and integration with @Transactional.
-
How to Implement Pessimistic Locking (@Lock) with Spring Boot + JPA - PESSIMISTIC_WRITE and Deadlock Prevention
Learn how to apply PESSIMISTIC_WRITE/READ using Spring Data's JPA @Lock, verify the issuance of SELECT ... FOR UPDATE, control timeouts with jakarta.persistence.lock.timeout, avoid deadlocks, and choose between pessimistic and optimistic locking—explained with real code.
-
How to Load Initial Data with data.sql and schema.sql in Spring Boot - When to Use Flyway/Liquibase Instead
A guide to SQL initialization with schema.sql/data.sql in Spring Boot. It covers why data.sql doesn't get executed, spring.sql.init.mode, the execution order relative to Hibernate ddl-auto, configuring defer-datasource-initialization, and criteria for choosing Flyway/Liquibase in production.
-
How to Work with Multiple DataSources in Spring Boot - Read/Write Separation and AbstractRoutingDataSource
A guide to implementing multiple DataSources in Spring Boot, covering two patterns: a static multi-DataSource configuration and dynamic read/write separation using AbstractRoutingDataSource. It walks through how to route to the primary/replica triggered by @Transactional(readOnly=true), organized with copy-and-run code.
-
Implementing a Synchronous HTTP Client with RestClient in Spring Boot 3.2 - Migrating from RestTemplate/WebClient
A hands-on guide to implementing RestClient, added in Spring Boot 3.2. This article covers GET/POST/PUT/DELETE with the fluent API, error handling with onStatus, connect/read timeouts, testing with MockRestServiceServer, migration steps from RestTemplate, and how to choose between WebClient and @HttpExchange.
-
Spring Boot Package Structure Best Practices - Choosing Between Layered and Feature-Based Approaches
For beginner to intermediate developers struggling with Spring Boot package structure, this guide compares the structure, benefits, and limitations of layered and feature-based approaches. It explains step by step how to choose based on project scale, how to maintain dependency direction, how to automatically test dependency rules with ArchUnit, and the path toward Spring Modulith.
-
Implementing Retry Processing with @Retryable in Spring Boot
This article explains how to use spring-retry's @Retryable in Spring Boot to implement automatic retries with exponential backoff for external API 503 errors and DB connection failures. It covers fallback handling with @Recover, the pitfalls of self-invocation, and when to choose Resilience4j instead, with code examples.
-
Building a Declarative HTTP Client with Spring Boot's HTTP Interface (@HttpExchange)
A walkthrough on implementing a declarative HTTP client using Spring Framework 6's standard @HttpExchange and HttpServiceProxyFactory, without adding Spring Cloud dependencies. Covers RestClient/WebClient adapter configuration, error handling, and how to choose between this approach and OpenFeign with practical examples.
-
How to Export and Read Excel Files in Spring Boot - Implementing Reports and Data Import with Apache POI
An implementation guide for exporting and reading Excel (xlsx) files with Spring Boot and Apache POI. Covers the basics of Workbook/Sheet/Cell, downloading via REST API, memory optimization for large datasets with SXSSFWorkbook, and parsing uploaded xlsx files, all with code examples.
-
How to Write Repository Layer Slice Tests with @DataJpaTest in Spring Boot - Choosing Between H2 and Testcontainers
A guide to writing slice tests focused on the Repository layer using @DataJpaTest in Spring Boot 3.x. Covers automatic rollback, TestEntityManager, switching between H2 and a real database via @AutoConfigureTestDatabase, verifying query methods and @Query, and when to combine Testcontainers — all with practical examples.
-
Thorough Comparison of Spring Boot's 3 Dependency Injection Methods - When to Use Constructor, Setter, and Field Injection
Compare the differences between Spring Boot's constructor, setter, and field injection from the perspectives of testability, null safety, and circular dependency detection. Explains combinations with @RequiredArgsConstructor and workarounds for circular dependencies with practical examples.
-
How to Dynamically Generate PDFs in Spring Boot - Report Output with OpenPDF and Thymeleaf
Implementation guide for dynamically generating PDFs in Spring Boot. Covers license comparison of OpenPDF/iText/Flying Saucer, conversion from Thymeleaf templates, Japanese font embedding, and download implementation with REST API.
-
How to Reduce Boilerplate Code with Lombok in Spring Boot
A practical explanation of the roles and proper usage of Lombok annotations frequently used in Spring Boot development (@Data, @Builder, @RequiredArgsConstructor, @Slf4j, etc.). Also covers pitfalls when used with JPA Entity and how to combine it with constructor injection.
-
Troubleshooting Guide for Spring Boot Application Startup Failures
For those panicking over 'APPLICATION FAILED TO START'. Based on Spring Boot 3.x, this guide reverse-looks-up 7 typical patterns from symptoms, including port conflicts, Bean duplication, circular references, missing DataSource configuration, and profile mistakes. It also covers how to read FailureAnalyzer messages and use the --debug flag with practical examples.
-
Spring REST Docs vs Springdoc OpenAPI: Differences and How to Choose
Compares Spring REST Docs and Springdoc OpenAPI from the perspectives of generation method, accuracy, and operational overhead, and explains selection criteria and combined usage patterns based on team size and API use cases.
-
How to Achieve a Modular Monolith with Spring Modulith
A practical guide to building a modular monolith using Spring Modulith 1.x. Explains defining package boundaries with @ApplicationModule, verifying boundaries with ApplicationModules.verify(), persisting events with the Event Publication Registry, and migration steps from existing ApplicationEvent implementations, all with concrete code examples.
-
How to Write Integration Tests with PostgreSQL, Kafka, and Redis Using Spring Boot Testcontainers
A practical guide to writing multi-container integration tests that simultaneously launch PostgreSQL, Kafka, and Redis using Spring Boot 3.1+'s @ServiceConnection, plus speeding up CI with reuse configuration.
-
Understanding Spring Boot Bean Scopes - When to Use singleton, prototype, request, and session
A thorough explanation of how Spring Boot's five Bean scopes (singleton/prototype/request/session/application) work and when to use each. Covers the pitfall of 'getting the same instance even though @Scope("prototype") was applied,' and introduces four workarounds using ObjectProvider, @Lookup, and jakarta.inject.Provider with implementation examples.
-
Customizing JSON Serialization with Jackson Configuration in Spring Boot - Date, Null Exclusion, and snake_case Guide
Solve common Jackson issues in Spring Boot such as 'LocalDateTime returned as array' and 'frontend requires snake_case'. This REST API implementation guide explains date formatting, null exclusion, snake_case conversion, and @JsonView/Mixin/custom Serializer with code examples.
-
Implementing the Transactional Outbox Pattern in Spring Boot
This article explains how to implement the Transactional Outbox pattern in Spring Boot to solve the dual-write problem between DB updates and Kafka messaging. It covers Outbox table design, relay via Poller, and comparison with Debezium CDC, complete with working code.
-
How to Implement Multi-Tenancy in Spring Boot
A guide to implementing multi-tenancy (Database/Schema/Shared-schema) with Spring Boot 3.2 and Hibernate 6.4, explained with comparison tables and working code. Covers everything from MultiTenantConnectionProvider to tenant resolution Filters using JWT/headers.
-
Implementing Spring Boot's GlobalExceptionHandler for Production Use
This article explains how to implement Spring Boot's GlobalExceptionHandler (@RestControllerAdvice) with production-ready quality. It introduces implementation patterns needed in the operational phase, such as stack trace logging, traceID assignment via MDC, and custom property extensions to ProblemDetail, with concrete code examples.
-
Database Migration Management with Liquibase in Spring Boot
A guide to introducing Liquibase in Spring Boot, covering XML/YAML/SQL changelog notation, how to write changeSets, executing rollbacks, and comparison and selection criteria against Flyway, complete with implementation code.
-
How to Implement Distributed Transactions in Microservices with the Saga Pattern in Spring Boot
A guide to implementing distributed transactions across microservices using the Saga pattern with Spring Boot + Kafka. Covers selection criteria for Choreography vs Orchestration types, compensating transaction design, and ensuring idempotency, complete with implementation code.
-
How to Implement Soft Delete with Spring Boot + JPA - Choosing Between @SQLDelete, @SQLRestriction, and Filter
This article explains how to transparently implement soft delete (logical deletion) with Spring Boot 3.x + Hibernate 6.4. It organizes a comparison between @SQLDelete + @SQLRestriction (formerly @Where) and @SoftDelete / @FilterDef so you can quickly choose the right approach, and summarizes common pitfalls such as unique constraint conflicts, restoration handling, and recording who deleted the record.
-
How to Prevent Duplicate @Scheduled Execution in Distributed Environments with Spring Boot and ShedLock
Learn how to solve the @Scheduled duplicate execution problem that occurs when running multiple Pods on Kubernetes and similar platforms using ShedLock. Covers LockProvider configuration for both JDBC and Redis, correct usage of @SchedulerLock, and common pitfalls.
-
How to Implement Server-Sent Events (SSE) in Spring Boot - SseEmitter / WebFlux Implementation Guide
A guide to implementing Server-Sent Events (SSE) in Spring Boot. Covers implementations using Spring MVC's SseEmitter and WebFlux's Flux<ServerSentEvent>, automatic reconnection with EventSource and resumption via Last-Event-ID, broadcasting to multiple clients, production pitfalls such as Nginx's proxy_buffering, and a practical example of relaying LLM streaming responses.
-
How to Implement JWT Refresh Tokens with Spring Security
A guide to issuing, rotating, and revoking access tokens and refresh tokens in Spring Boot, including Redis persistence and reuse detection.
-
How to Implement Idempotency (Idempotency-Key) in Spring Boot REST APIs - Preventing Double Charges and Double Clicks
Explains how to implement the Idempotency-Key header approach in Spring Boot to prevent double charges and double execution caused by double-clicks in payment APIs. Covers implementation code using OncePerRequestFilter and Redis, lock control for concurrent requests, TTL design, and production operation considerations from a practical perspective.
-
How to Speed Up Spring Boot Application Startup - Reducing Time with CDS, AOT, and Lazy Initialization
Spring Boot apps starting too slowly, causing Pods to miss readiness probes, or breaking your focus during local rebuilds—this guide solves those problems with practical steps. Learn how to identify bottlenecks with Actuator startup, then progressively apply lazy initialization, AutoConfig exclusion, CDS, and AOT to consistently reduce startup time.
-
How to Implement Optimistic Locking (@Version) with JPA in Spring Boot to Prevent Concurrent Update Conflicts
Learn how to prevent 'Lost Update' issues that occur in e-commerce inventory updates and reservation systems using the @Version annotation. Covers OptimisticLockException handling, retry strategies with Spring Retry, and writing concurrency tests with practical code examples.
-
How to Implement Type-Safe Dynamic Queries with QueryDSL in Spring Boot
A practical guide to integrating QueryDSL into Spring Boot, covering Q-type class generation via APT, dynamic query implementation with JPAQueryFactory, and pagination integration. Includes a comparison with Specification.
-
How to Implement API Rate Limiting in Spring Boot - Limiting Request Count with Bucket4j and Filter
Step-by-step guide to implementing rate limiting per IP and per API key from scratch by combining Bucket4j with Spring Boot's Servlet Filter. Covers how to return HTTP 429 on limit exceeded, and clarifies the differences in use cases compared to Resilience4j @RateLimiter.
-
Understanding Spring Security CSRF Protection Correctly - Configuration Differences Between REST APIs and Web Apps
Solve the cause of POST returning 403 in Spring Security by understanding the CSRF mechanism. From why `csrf().disable()` is correct for REST APIs, the required settings for Thymeleaf forms, to AJAX support via `CookieCsrfTokenRepository.withHttpOnlyFalse()`, organized with Spring Security 6 Lambda DSL implementation examples.
-
How to Implement Dynamic Queries with Spring Data JPA Specifications - Handling Search Form Filtering with JpaSpecificationExecutor
An implementation guide for Spring Data JPA Specifications that eliminates if-statement hell in search forms. Covers setting up JpaSpecificationExecutor, safely skipping null conditions, combining multiple conditions with AND/OR, integrating with pagination, and choosing between Specifications and QueryDSL, all explained with practical code examples.
-
How to Properly Configure and Tune Spring Boot's HikariCP Connection Pool - Why the Default of 10 Isn't Enough
Tuning steps to eliminate 'Connection is not available' errors in Spring Boot's HikariCP. Covers the default maximumPoolSize of 10 and the official formula (cores × 2 + 1), revising connectionTimeout from 30s to 3s, the relationship between maxLifetime and wait_timeout, and leak detection with leakDetectionThreshold, all with implementation examples. Includes comparison data showing timeout error rates reduced from 40% to 3% through configuration changes.
-
How to Write Controller Unit Tests with MockMvc in Spring Boot - Introduction to @WebMvcTest
Achieve fast, DB-free, copy-paste-ready Controller unit tests with @WebMvcTest and MockMvc. Explains how to mock Services with @MockBean, validate JSON with jsonPath, handle validation errors (400), and integrate Security (@WithMockUser) with practical examples.
-
How to Validate Spring Boot @ConfigurationProperties with Bean Validation - A Fail Fast Implementation Guide to Detect Configuration Errors at Startup
Learn how to combine Spring Boot's @ConfigurationProperties with Bean Validation (@Validated/@NotBlank/@Pattern) to instantly detect configuration mistakes at application startup before they cause production incidents. Covers @Valid propagation for nested validation, how to read startup error messages, and lightweight testing with ApplicationContextRunner, all with implementation examples.
-
How to Standardize Error Responses with Problem Details (RFC 9457) in Spring Boot 3.x
Learn how to unify error responses with Problem Details (RFC 9457), natively supported in Spring Boot 3.x. This guide covers the spring.mvc.problemdetails.enabled setting, how to use the ProblemDetail class and ErrorResponse, integration with @ControllerAdvice and ResponseEntityExceptionHandler, migration steps from Spring Boot 2.x, and application to Spring Security and validation errors, all with code examples.
-
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 - From import Setup to Practice
A practical guide to introducing WireMock into Spring Boot tests and defining external API stubs at the HTTP level, covering success cases, error cases, and timeouts. Also explains the correct import statement for WireMock 3.x's new package org.wiremock.client.WireMock, as well as criteria for choosing between Mockito and WireMock.
-
How to Upload and Download Files to AWS S3 with Spring Boot - AWS SDK v2 and Presigned URL Support
A guide to implementing file upload and download from Spring Boot applications to AWS S3 using AWS SDK v2. Covers how to choose between spring-cloud-aws 3.x, Service implementation with MultipartFile support, presigned URL generation, IAM role authentication, and least-privilege policy examples with copy-paste ready samples.
-
How to Implement Internationalization (i18n) in Spring Boot - Using MessageSource and LocaleResolver
An implementation guide for achieving internationalization (i18n) in Spring Boot REST APIs. Covers everything from language switching via the Accept-Language header, locale fallback in messages.properties, configuring MessageSource and AcceptHeaderLocaleResolver, localizing @Valid validation error messages, to 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 REST API CRUD with Spring Boot - Basic Structure of Controller, Service, and Repository
A step-by-step guide to implementing REST API CRUD (Create, Read, Update, Delete) with Spring Boot using a three-layer structure of Controller, Service, and Repository. Get the four GET/POST/PUT/DELETE endpoints running via copy-paste, with end-to-end coverage including verification using curl.
-
Implementing Kafka Producer and Consumer in Spring Boot - Beginner's Guide with Sample Code
A practical guide to implementing Kafka Producer and Consumer in a Spring Boot 3.x application from scratch using spring-kafka. Quickly start a broker with Docker Compose, then learn the basics of KafkaTemplate and @KafkaListener, retries and Dead Letter Topic forwarding with DefaultErrorHandler, and testing with @EmbeddedKafka—all explained with a code-centric approach.
-
Spring Security Method Security - How to Implement RBAC with @PreAuthorize
A guide to implementing method-level Role-Based Access Control (RBAC) in Spring Boot using @PreAuthorize/@PostAuthorize/@Secured. Learn how to enable @EnableMethodSecurity, the differences between hasRole/hasAuthority, owner checks with SpEL, and testing with @WithMockUser, all with code examples.
-
How to Implement Real-Time Communication with WebSocket in Spring Boot - Basics of STOMP and SockJS
Learn how to quickly run a broadcast-style chat with Spring Boot + STOMP + SockJS, explained through a three-layer structure of configuration class, @MessageMapping, and SimpMessagingTemplate. Covers one-to-one messaging, retrieving authenticated users via Principal, and scaling with an external broker.
-
How to Use Redis with Spring Boot - Implementation Patterns for Session Management, Caching, and Pub/Sub
Learn how to solve common issues such as sessions not being shared across multiple instances and switching the backend of @Cacheable using Redis. This article covers connection configuration for spring-boot-starter-data-redis, session externalization with Spring Session, RedisCacheManager, and Pub/Sub implementation, with code examples for each 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 - @Constraint/ConstraintValidator Implementation Guide
A step-by-step guide to creating custom validations with @Constraint and ConstraintValidator, covering three patterns: phone number format, email duplication check (using DI), and password confirmation (cross-field). Encapsulate rules that @NotBlank / @Pattern cannot handle into reusable annotations and consolidate validation logic scattered across the Service layer.
-
Spring Boot Thymeleaf Server-Side Rendering Implementation Guide - Forms, Validation, and Security
A comprehensive implementation tutorial for Spring Boot 3.x × Thymeleaf 3.1, covering HTML responses, form handling, Bean Validation error display, and Spring Security integration (CSRF/authentication display switching). Based on code examples that work as-is.
-
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.x to 3.x Migration Guide - Java 17 Required with Checklist
Explains the 2.x→3.x migration steps with practical code examples in response to Spring Boot 2.7 end-of-life (EOL) and the Java 17 requirement. Organizes javax→jakarta replacement, SecurityFilterChain migration, and spring.factories deprecation handling with a checklist, providing the shortest route to understanding the causes and solutions for compilation/startup errors.
-
How to Implement Circuit Breaker with Resilience4j in Spring Boot - Spring Boot 3.x Guide
Learn how to implement circuit breakers in Spring Boot 3.x using Resilience4j, the successor to Hystrix. This guide covers how to use @CircuitBreaker, @Retry, @RateLimiter, Bulkhead, and TimeLimiter, fallback design, parameter tuning in application.yml, and state monitoring with Actuator, all 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.
-
Difference Between Interceptor and Filter in Spring Boot - With Implementation Samples for Request Pre/Post Processing
For those wondering which to use between Spring Boot's Filter and HandlerInterceptor, this article first presents the criteria for choosing between them. It organizes the differences in execution timing, Spring DI management, and available information, then explains use cases such as authentication checks, request logging, CORS, and exception handling with implementation samples.
-
Database Migration Management with Flyway in Spring Boot - An Introductory Guide from Version Control to Production Deployment
A practical guide to safely version-controlling database schemas with Flyway in Spring Boot applications. Explains spring-boot-starter-flyway setup, application.properties configuration, the flyway_schema_history table mechanism, handling existing databases with baseline-on-migrate, and troubleshooting using flywayRepair with concrete examples.
-
How to Safely Process Large Data with Spring Batch - Introductory Guide to Job/Step/Chunk Processing
A guide to implementing large-scale batch processing with Spring Batch, complete with sample code that even beginners can follow. Covers the basic structure of Job/Step/ItemReader/ItemWriter, memory-efficient implementation using chunk processing, transaction management, and error handling with skip and retry, all using the latest syntax compatible with Spring Boot 3.x.
-
How to Implement Asynchronous Processing in Spring Boot - Using @Async and @EnableAsync
An implementation guide for @Async / @EnableAsync, compatible with Virtual Threads in Spring Boot 3.2+ / Java 21. Learn how to speed up your API by running email sending and external API calls in the background, with production know-how covering ThreadPoolTaskExecutor sizing, RejectedExecutionHandler, graceful shutdown, MDC propagation (TaskDecorator), and CompletableFuture, all explained with implementation examples.
-
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 Spring Cache Abstraction mechanics, how to use @Cacheable, @CacheEvict, and @CachePut, switching between Caffeine and Redis, and measuring hit rates with Micrometer, all with hands-on code. For beginner to intermediate developers who want to improve response latency from duplicate DB or external API calls with just a few annotations.
-
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.
-
Getting Started with Authentication in Spring Boot Using Spring Security - From Basic Authentication to Form Authentication
A beginner-friendly tutorial for implementing authentication step by step with Spring Security in Spring Boot. Covers the basics of SecurityFilterChain, the BCrypt password encoder, Basic authentication (verified with curl), form authentication, logout, and custom login pages, carefully explaining configuration points that are easy to stumble on.
-
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.
-
Have You Ever Been Unsure How to Write Spring Data JPA Query Methods?
A reference table summarizing the naming conventions of Spring Data JPA query methods (findBy/existsBy/countBy/deleteBy). Check keywords like Containing/StartingWith/GreaterThan/Between/In/IsNull along with their generated SQL and usage examples in a quick-reference table. Also explains custom queries with @Query, sorting, and paging with practical examples.
-
Introduction to Spring Boot JPA Relationship Mapping - How to Use @OneToMany/@ManyToOne/@ManyToMany and mappedBy
A beginner-friendly explanation of @OneToMany/@ManyToOne/@ManyToMany/mappedBy in Spring Boot JPA. Resolves common pitfalls with code examples covering the differences between bidirectional/unidirectional relationships, cascade, FetchType, the N+1 problem, and circular reference countermeasures.
-
Writing Tests in Spring Boot - Introduction to Unit Testing with JUnit and Mockito
Learn how to write Spring Boot unit tests with JUnit 5 and Mockito, explained step by step for the Service layer (@Mock/@InjectMocks) and Controller layer (@WebMvcTest/@MockBean/MockMvc). Master the Given-When-Then pattern, success/failure cases, and assertThrows through concrete code examples.
-
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 Implement Validation Simply with Spring Boot @Valid Annotation - Usage and Error Handling
A concise guide to using the Spring Boot @Valid annotation with code examples. Covers automatic validation with @RequestBody, key constraints like @NotBlank/@Email/@Size, recursive validation of nested DTOs, differences from @Validated, and standardizing error responses for MethodArgumentNotValidException with practical implementation examples.
-
Spring @Bean "Name" Guide - When to Set It? How Does It Work? What's the Priority?
A practical guide to the role of the 'name' attribute on Spring Boot's @Bean. Covers default naming conventions (method name = Bean name), how to assign explicit names/aliases, the priority of @Qualifier, @Primary, and parameter names, avoiding Bean name collisions, and tips for using constants, all with code examples.
-
What are @Configuration and @Bean in Spring Boot? Differences from @Component and How to Use Them
Explains the differences between @Configuration and @Bean in Spring Boot, and how to use them alongside @Component with practical examples. Covers Bean registration for external libraries, argument injection in @Bean methods, CGLIB proxy behavior, and how to swap beans in tests, organized with clear decision criteria.
-
Getting Started with Spring Boot Actuator
A practical guide covering everything from introducing spring-boot-starter-actuator, configuring health/info/metrics endpoint exposure, a minimal application.yml, Prometheus integration, to secure production-ready exposure configurations. A gentle summary for those touching Spring Boot Actuator for the first time.
-
How to Return Unified Error Responses in Spring Boot REST API - Using @ControllerAdvice and @ExceptionHandler (@RestControllerAdvice / ResponseEntityExceptionHandler Support)
Are you struggling with inconsistent error responses across Controllers? This article explains how to use @ControllerAdvice, @RestControllerAdvice, and @ExceptionHandler in Spring Boot REST API to return validation errors, business errors, and system errors in a unified JSON format. Learn design patterns and code examples for extending ResponseEntityExceptionHandler to standardize Spring MVC default exceptions as well.
-
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 and How to Use It
A beginner-friendly explanation of what @Component is in Spring Boot. Covers the differences from @Bean, criteria for choosing between them, the relationship with @Service/@Repository, and practical usage including constructor injection 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.
-
What is Spring Boot DI (Dependency Injection)? Mechanism, Syntax, and Benefits Explained [For Beginners]
A beginner-friendly explanation of Spring Boot DI (Dependency Injection). Covers why using new is problematic, how to write constructor injection, and concrete benefits such as easier testing, swappable implementations, and avoiding unnecessary instance creation, all with sample code.
-
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.