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 Tune Embedded Tomcat Thread Count in Spring Boot - Deciding server.tomcat.threads.max, max-connections, and accept-count
This article explains at which stage of request handling server.tomcat.threads.max, threads.min-spare, max-connections, and accept-count take effect in Spring Boot 3.x's embedded Tomcat, and walks through a procedure for choosing values with evidence using Actuator's tomcat.threads.* metrics and load testing. It also covers alignment with HikariCP's maximumPoolSize and the differences when Virtual Threads are enabled.
-
How to Connect Spring Boot to MySQL - application.yml Configuration, JDBC URL Parameters, and Time Zone/Character Encoding Pitfalls
A step-by-step guide to connecting Spring Boot 3.x to MySQL 8, covering Docker Compose startup, application.yml configuration, and connectivity checks. Also covers recommended JDBC URL parameter values and how to fix the Public Key Retrieval error, date/time offsets, and utf8mb4 garbled characters.
-
How to Implement Pagination with Spring Boot + MyBatis - Choosing Between PageHelper, RowBounds, and Hand-Written LIMIT/OFFSET
Compares three approaches to paginating list APIs in Spring Boot + MyBatis (hand-written LIMIT/OFFSET, RowBounds, and PageHelper) in terms of generated SQL, count retrieval, sorting, and extra dependencies. Explains why RowBounds results in in-memory pagination, the thread-local pitfalls of PageHelper and its helperDialect setting, and how to convert to Spring Data's Pageable, all with ready-to-run code.
-
Mastering Mockito in Spring Boot Service Layer Tests - when, verify, ArgumentCaptor, and doThrow in Practice
Hands-on guide to Mockito's when/thenReturn, verify (times, never, inOrder), ArgumentCaptor, and doThrow/doAnswer for void methods, using OrderService tests. Also covers how to fix UnnecessaryStubbingException and InvalidUseOfMatchersException, and when to use @InjectMocks versus @MockitoBean.
-
How to Validate List<DTO>, @RequestParam, and @PathVariable in Spring Boot - Why @Valid Doesn't Work and How to Handle the 3 Exceptions
A reverse-lookup guide to why element validation of a List-typed DTO annotated with @Valid, or @Min on @RequestParam/@PathVariable, doesn't work in Spring Boot 3.x, and how to fix it. Covers the differences between the 3 exceptions, unified error responses with @RestControllerAdvice, and indexed messages in the users[1].name format.
-
Spring Boot Validation Annotations Cheat Sheet - From the Differences Between @NotNull/@NotEmpty/@NotBlank to Custom Messages
A cheat sheet of the standard constraint annotations available in Spring Boot 3.x (Jakarta Bean Validation 3.0), listing each one's target types, behavior on null, and default message. Covers the differences between @NotNull/@NotEmpty/@NotBlank, @Size vs @Length, choosing between numeric, date-time, and string constraints, Hibernate Validator-specific constraints, and overriding messages with localized text via ValidationMessages.properties or messages.properties.
-
Which Spring Boot Authentication Method Should You Choose? Comparing Session, JWT, OAuth2, and API Key with a Selection Flowchart
Compare Spring Boot authentication methods (Session, JWT, OAuth2, API Key) by application architecture. Use the selection flowchart and comparison table to decide which method fits your app, then move from a minimal SecurityFilterChain configuration to each implementation guide.
-
Spring Boot Test Annotations Cheat Sheet - How to Choose Between @SpringBootTest, @WebMvcTest, and @DataJpaTest
A cheat sheet and decision flow for choosing the right Spring Boot test annotation. Covers the differences in startup scope and speed between @SpringBootTest, @WebMvcTest, @DataJpaTest, @JsonTest, and @RestClientTest, with layer-by-layer explanations of how to combine them with @MockitoBean, MockMvc, and Testcontainers.
-
Why @Transactional, @Cacheable, and @Async Don't Work in Spring Boot - Understanding AOP Proxies and Self-Invocation to Fix It
@Transactional doesn't roll back, @Cacheable hits the DB every time, @Async runs synchronously. All of these are caused by how Spring AOP proxies work. This article isolates five patterns - self-invocation, private/final methods, new, and missing enablement - with reproducible code and diagnostic steps, then compares workarounds such as extracting to a separate Bean, self-injection, and TransactionTemplate.
-
How to Use the @Query Annotation in Spring Boot + Spring Data JPA - From JPQL and Native SQL to Update Queries with @Modifying
A hands-on guide to mastering the @Query annotation in Spring Boot + Spring Data JPA. Covers the basics of JPQL and @Param, when to use nativeQuery=true, UPDATE/DELETE with @Modifying + @Transactional, countQuery when combined with Pageable, SpEL (:#{}), and escaping LIKE searches, all explained with copy-and-paste-ready repository code.
-
How to Implement Session Management with Spring Session + Redis in Spring Boot - Sharing Sessions Across Multiple Instances
An implementation guide to solving the problem of login state being lost when scaling out a Spring Boot app to multiple instances, using Spring Session + Redis. Covers everything end to end: adding dependencies, configuring spring.session.*, cookie design, Spring Security integration, debugging with redis-cli, and verifying behavior across two instances.
-
Differences Between @Service, @Repository, and @Controller in Spring Boot and How to Use Them - From Their Relationship with @Component to Exception Translation
@Service, @Repository, and @Controller are all derived from @Component, but they differ in actual effects beyond DI registration, such as exception translation in @Repository and handler mapping in @Controller. This article demonstrates the differences with source code and verification code, and explains the criteria for choosing annotations for each layer with a quick reference table.
-
How to Use Quartz Scheduler in Spring Boot - Persistent Jobs, Cron, and Dynamic Scheduling (When to Use It vs. @Scheduled)
Learn how to use spring-boot-starter-quartz in Spring Boot, covering JobDetail/Trigger definitions, persisting jobs to a database with the JDBC JobStore, dynamically registering and modifying jobs at runtime, and preventing duplicate execution across a cluster with isClustered, all with code examples. It also clarifies the criteria for when to use it versus @Scheduled and ShedLock.
-
How to Speed Up Bulk INSERTs with Spring Data JPA - hibernate.jdbc.batch_size and Batching saveAll
Explains why calling saveAll() still results in INSERTs being executed one at a time, covering the mechanics of hibernate.jdbc.batch_size, order_inserts, and IDENTITY generation. From PostgreSQL's reWriteBatchedInserts to a comparison with JdbcTemplate.batchUpdate, it walks through the steps to speed up bulk INSERTs while verifying with SQL logs.
-
Implementing Database Authentication with Spring Security - Persisting Users with UserDetailsService and JdbcUserDetailsManager
This article explains the standard pattern for moving away from in-memory users and authenticating against users stored in your own users table. It covers, with code, how to write your own UserDetailsService, wire it into DaoAuthenticationProvider, use JdbcUserDetailsManager with the standard schema, register and verify passwords with BCrypt, and handle account disabling.
-
How to Use MyBatis with Spring Boot - An Implementation Guide to Mapper Definitions, Dynamic SQL, and Result Mapping
An implementation guide to integrating MyBatis into Spring Boot from scratch. It covers everything from adding the mybatis-spring-boot-starter dependency, defining Mappers using both annotation and XML notations, dynamic SQL with the if and foreach tags, mapping join results with resultMap, the safety of #{} vs ${}, and @Transactional integration—all explained with working code.
-
How to Persist enums to a Database with Spring Boot + JPA - Choosing Between @Enumerated(EnumType.STRING) and AttributeConverter
A guide to persisting enum fields to database columns with Spring Boot + JPA. Covers the difference between @Enumerated(STRING/ORDINAL), the dangers of ORDINAL, implementing an AttributeConverter for custom code values, and criteria for choosing between the two approaches, with practical examples.
-
How to Implement gRPC Services and Clients in Spring Boot - Protocol Buffers and grpc-spring-boot Support
A hands-on guide to implementing gRPC in Spring Boot, covering dependency setup, code generation from .proto files, server implementation with @GrpcService, client calls with @GrpcClient, error conversion, authentication/logging via interceptors, and how to choose between REST and GraphQL.
-
@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.
-
Spring Boot Application Won't Start? How to Isolate the Cause and Fix It
For anyone panicking at 'APPLICATION FAILED TO START'. Targeting Spring Boot 3.x, this guide walks through 7 typical patterns, including port conflicts, duplicate Beans, circular references, missing DataSource configuration, and profile mistakes, using a symptom-first reverse lookup. It also covers how to read FailureAnalyzer messages and how to use the --debug flag, with real 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 guide to the behavior and use cases of Spring Boot's five Bean scopes (singleton/prototype/request/session/application). Covers the pitfall where @Scope("prototype") still returns the same instance, and four workarounds using ObjectProvider, @Lookup, and jakarta.inject.Provider with implementation examples.
-
Customizing JSON Serialization with Jackson in Spring Boot - A Guide to Date Formatting, Null Exclusion, and snake_case
Solve common Jackson issues in Spring Boot such as 'LocalDateTime is returned as an array' and 'the frontend requires snake_case'. This REST API implementation guide covers date formatting, null exclusion, snake_case conversion, @JsonView, Mixins, and custom Serializers 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 Filters
Learn how to implement soft delete transparently with Spring Boot 3.x + Hibernate 6.4. We compare @SQLDelete + @SQLRestriction (formerly @Where) with @SoftDelete and @FilterDef so you can choose the right approach quickly, and cover common pitfalls such as unique constraint conflicts, restore operations, and recording who performed the deletion.
-
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
Learn how to implement Server-Sent Events (SSE) in Spring Boot. This guide covers implementations using Spring MVC's SseEmitter and WebFlux's Flux of ServerSentEvent, automatic reconnection with EventSource and resumption via Last-Event-ID, broadcasting to multiple clients, production pitfalls such as Nginx proxy_buffering, and a real-world 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 a Spring Boot REST API - Preventing Double Charges and Double-Clicks
Learn how to implement the Idempotency-Key header pattern in Spring Boot to prevent double charges and duplicate execution caused by double-clicks on payment APIs. Covers implementation code using OncePerRequestFilter and Redis, lock control for concurrent requests, TTL design, and production operation caveats 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 Specification - Supporting Search Form Filtering with JpaSpecificationExecutor
A hands-on guide to Spring Data JPA Specification 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 Specification and QueryDSL, all with practical code examples.
-
How to Correctly Configure and Tune the HikariCP Connection Pool in Spring Boot - Why the Default of 10 Isn't Enough
A tuning walkthrough for eliminating "Connection is not available" errors with HikariCP in Spring Boot. Covers the default maximumPoolSize of 10 and the official sizing formula (cores × 2 + 1), reducing 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 the timeout error rate dropping from 40% to 3% after revisiting the configuration.
-
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 for Detecting Configuration Errors at Startup
Learn how to combine Spring Boot @ConfigurationProperties with Bean Validation (@Validated/@NotBlank/@Pattern) to catch configuration errors at application startup, before they become production incidents. Covers nested validation with @Valid propagation, 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 using Problem Details (RFC 9457), now supported out of the box in Spring Boot 3.x. This guide covers the spring.mvc.problemdetails.enabled setting, how to use the ProblemDetail class and ErrorResponse, integrating @ControllerAdvice with ResponseEntityExceptionHandler, migration steps from Spring Boot 2.x, and applying Problem Details 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 approaches to versioning REST APIs in Spring Boot (URI path, custom header, and Accept header) with working implementation code. Covers decision criteria for choosing the approach that fits your team's API characteristics, plus a Swagger UI integration example.
-
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
This article explains how to implement file upload and download from a Spring Boot application to AWS S3 using AWS SDK v2. It covers how to choose between the SDK and spring-cloud-aws 3.x, a Service implementation that handles MultipartFile, presigned URL generation, IAM role authentication, and an example least-privilege policy, all with copy-and-paste-ready sample code.
-
How to Implement Internationalization (i18n) in Spring Boot - Using MessageSource and LocaleResolver
A practical guide to implementing internationalization (i18n) in Spring Boot REST APIs. Covers language switching via the Accept-Language header, locale fallback with messages.properties, configuring MessageSource and AcceptHeaderLocaleResolver, localizing @Valid validation error messages, and returning multilingual error responses with @RestControllerAdvice, all in one end-to-end walkthrough.
-
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 in Spring Boot - The Basic Controller, Service, and Repository Structure
A step-by-step guide to implementing REST API CRUD (Create, Read, Update, Delete) in Spring Boot using the three-layer Controller, Service, and Repository architecture. Get the four GET/POST/PUT/DELETE endpoints running with copy-paste code, and verify them end-to-end with 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 - STOMP and SockJS Basics
A step-by-step guide to getting a broadcast-style chat running quickly with Spring Boot + STOMP + SockJS, explained through a three-layer structure: the configuration class, @MessageMapping, and SimpMessagingTemplate. Also covers one-to-one messaging, retrieving the authenticated user 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.
-
How to Configure CORS in Spring Boot - Choosing Between @CrossOrigin and WebMvcConfigurer
A practical guide to resolving CORS errors when calling a Spring Boot REST API from frontends like React or Vue. Covers when to use each of the three approaches (@CrossOrigin, WebMvcConfigurer, and SecurityFilterChain), plus the pitfalls to watch for when introducing Spring Security.
-
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.
-
Server-Side Rendering with Thymeleaf in Spring Boot: A Complete Guide to Forms, Validation, and Security Integration
A hands-on tutorial covering Spring Boot 3.x and Thymeleaf 3.1 end to end: HTML responses, form handling, Bean Validation error display, and Spring Security integration (CSRF and auth-aware view switching). Built around runnable code examples you can use 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.
-
Introducing Distributed Tracing with Micrometer Tracing and Zipkin in Spring Boot 3.2+
A step-by-step guide to introducing distributed tracing with Micrometer Tracing and Zipkin in Spring Boot 3.2 and later. Covers the migration path after Spring Cloud Sleuth was discontinued, trace ID propagation between services, and how to verify traces in 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 a Circuit Breaker with Resilience4j in Spring Boot - A Guide for Spring Boot 3.x
Learn how to implement a circuit breaker in Spring Boot 3.x using Resilience4j, the successor to Hystrix. This guide covers @CircuitBreaker, @Retry, @RateLimiter, Bulkhead, and TimeLimiter usage, fallback design, parameter tuning in application.yml, and checking state via 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 in Prometheus via Micrometer and visualizing them in real time on Grafana dashboards. Also covers custom metrics implementation examples (Counter and Gauge) and security considerations for production operation.
-
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.
-
Managing Database Migrations with Flyway in Spring Boot - A Practical Guide from Version Control to Production Deployment
A practical guide to safely versioning your database schema with Flyway in Spring Boot applications. Covers adding spring-boot-starter-flyway, configuring application.properties, how the flyway_schema_history table works, handling existing databases with baseline-on-migrate, and troubleshooting with flywayRepair, all 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 Improvements with @Cacheable
A hands-on guide covering how Spring Cache Abstraction works, how to use @Cacheable, @CacheEvict, and @CachePut, switching to Caffeine and Redis, and measuring hit rates with Micrometer, all with practical code examples. Aimed at beginner-to-intermediate developers who want to fix response latency caused by redundant DB or external API calls with just a few lines of 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.
-
How to Configure Logging in Spring Boot - Logback and SLF4J Basics and Practical Configuration
A guide to Spring Boot logging configuration from basics to practice. Learn step by step how to change log levels in application.properties, output to files with logback-spring.xml, set up log rotation, and configure per-environment settings.
-
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 - Choosing the Right Propagation and Isolation Levels
A guide to transaction management using the @Transactional annotation in Spring Boot, from basics to practical use. Covers default behavior, how to choose among the 7 propagation levels and 4 isolation levels, and how to fix common pitfalls where rollback silently fails (checked exceptions, self-invocation), with working examples.
-
Getting Started with Authentication in Spring Boot Using Spring Security - From Basic Auth to Form Login
A beginner-friendly tutorial for implementing authentication step by step with Spring Security in Spring Boot. Covers SecurityFilterChain fundamentals, the BCrypt password encoder, Basic authentication (verified with curl), form login, logout, and custom login pages, with careful explanations of the configuration points where beginners commonly get stuck.
-
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 with application.properties/yml in Spring Boot - When to Use @Value vs @ConfigurationProperties
A practical guide covering the basic syntax of Spring Boot configuration files, how to choose between @Value and @ConfigurationProperties in real-world projects, and configuration management using environment variables and placeholders.
-
Spring Data JPA Query Methods: A Complete Naming Convention Cheat Sheet
A cheat sheet organizing Spring Data JPA query method naming conventions (findBy/existsBy/countBy/deleteBy) in reference tables. Check keywords like Containing/StartingWith/GreaterThan/Between/In/IsNull alongside the generated SQL and usage examples. Also covers custom queries with @Query, sorting, and paging with practical examples.
-
Introduction to JPA Association Mapping in Spring Boot - How to Use @OneToMany/@ManyToOne/@ManyToMany and mappedBy
A beginner-friendly guide to @OneToMany, @ManyToOne, @ManyToMany, and mappedBy in Spring Boot JPA. Covers bidirectional vs. unidirectional relationships, cascade, FetchType, the N+1 problem, and circular reference handling with code examples to resolve common pitfalls.
-
Writing Tests in Spring Boot - An Introduction to Unit Testing with JUnit and Mockito
A step-by-step guide to writing Spring Boot unit tests with JUnit 5 and Mockito, split into the Service layer (@Mock/@InjectMocks) and the Controller layer (@WebMvcTest/@MockBean/MockMvc). Learn the Given-When-Then pattern, success and failure cases, and assertThrows through concrete code examples.
-
How to Safely Switch Environment-Specific Configuration with Spring Boot Profiles
Spring Boot Profiles let you switch configuration between development, staging, and production. This guide clearly explains how to split application.yml, how to activate profiles, and common pitfalls to avoid.
-
How to Implement Group Validation and Method Validation with Spring Boot's @Validated Annotation
A step-by-step guide to safely integrating group validation and Service-layer method validation using Spring Boot's @Validated, covering the differences from @Valid and exception handling.
-
How to Implement Validation Simply with the Spring Boot @Valid Annotation - Usage and Error Handling
A concise guide with code to using the Spring Boot @Valid annotation. Covers automatic validation with @RequestBody, key constraints such as @NotBlank/@Email/@Size, recursive validation of nested DTOs, the difference from @Validated, and standardizing error responses for MethodArgumentNotValidException with 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
A practical guide to the differences between @Configuration and @Bean in Spring Boot and when to use them versus @Component, with real examples. Covers registering beans from external libraries, injecting arguments into @Bean methods, CGLIB proxy behavior, and replacing beans in tests, 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 APIs - Using @ControllerAdvice and @ExceptionHandler (with @RestControllerAdvice / ResponseEntityExceptionHandler)
Struggling with inconsistent error responses across Controllers? This guide explains how to use @ControllerAdvice, @RestControllerAdvice, and @ExceptionHandler in Spring Boot REST APIs to return validation errors, business errors, and system errors in a unified JSON format. It also covers the design pattern of extending ResponseEntityExceptionHandler to standardize Spring MVC's built-in exceptions, with code examples.
-
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 guide to @Component in Spring Boot. Learn the differences from @Bean, criteria for choosing between them, how it relates to @Service and @Repository, and practical usage including constructor injection, with code examples.
-
What Is a Spring Boot Starter?
A beginner-friendly explanation of what Spring Boot Starters do and how they work. Learn how to choose key Starters such as spring-boot-starter-web, why they simplify dependency management, and common pitfalls to watch out for.
-
What Is Spring AOP? How It Works and How to Use It, with Sample Code
A clear explanation of how Spring AOP (Aspect-Oriented Programming) works. Learn how to separate cross-cutting concerns such as logging and authorization checks from your business logic, with Spring Boot configuration steps and sample code.
-
What Is DI (Dependency Injection) in Spring Boot? How It Works, How to Write It, and Its Benefits [Beginner's Guide]
A beginner-friendly explanation of DI (Dependency Injection) in Spring Boot. Learn why using new is not enough, how to write constructor injection, and concrete benefits such as easier testing, swappable implementations, and no unnecessary instances, all with sample code.
-
What Is the Difference Between Spring and Spring Boot? A Comparison of Configuration, Startup, and Dependencies
Spring is the core framework that forms the foundation of Java development, while Spring Boot sits on top of Spring to simplify configuration, dependency management, and startup. This article organizes the differences clearly with a comparison table and code examples, and explains which one beginners should start with and how to choose between them in real-world projects.
-
Why Is Spring Boot So Widely Used in Enterprise Application Development?
Explains why Spring Boot is chosen for enterprise systems from the perspectives of development speed, maintainability, and operability. Covers which projects it suits and which it doesn't, plus pre-adoption checkpoints, all from a practical standpoint.