Spring Framework
Spring Framework is a popular opensource lightweight application framework and Inversion of Control (IoC) container for the Java platform. This page contains core concepts, Spring Boot how-to guides, and best practices with code examples.
Spring Core Concepts
13 articlesWhat is IoC (Inversion of Control) and IoC Container
The IoC principle explained, ApplicationContext vs BeanFactory, and how Spring manages object creation and wiring.
Hello World: Spring Beans Using XML Based Configuration
Creating your first Spring application, defining beans in XML, loading the context, and wiring dependencies.
Dependency Injection: Constructor, Setter and Field
Constructor injection vs setter injection vs field injection, when to use each, and circular dependency pitfalls.
Stereotype Annotations: @Component, @Service, @Repository, @Controller
Component scanning, the role of each stereotype annotation, and how Spring uses them for auto-detection.
Bean Scopes: Singleton, Prototype, Request, Session
Default singleton scope vs prototype, web-aware scopes, and the @Scope annotation.
Bean Lifecycle: @PostConstruct and @PreDestroy
Spring bean lifecycle phases, init and destroy callbacks, InitializingBean interface, and DisposableBean.
Java Based Configuration: @Configuration and @Bean
Replacing XML with @Configuration classes, @Bean methods, @Import, and mixing Java config with component scanning.
Aspect Oriented Programming: @Aspect, @Before, @After, @Around
Cross-cutting concerns with AOP, pointcut expressions, join points, advice types, and @EnableAspectJAutoProxy.
Spring: @Transactional & Transaction Management
@Transactional deep dive: propagation, isolation levels, rollback rules, and common pitfalls.
Spring: Application Events & @EventListener
Spring application events: publishing custom events, @EventListener, async events, and built-in lifecycle events.
Spring: Cache Abstraction (@Cacheable, @CacheEvict)
Spring cache abstraction: @Cacheable, @CachePut, @CacheEvict with ConcurrentMap, Caffeine and Redis backends.
Spring: Task Scheduling with @Scheduled
@Scheduled for task scheduling: fixed rate, fixed delay, cron expressions, and dynamic scheduling with TaskScheduler.
Spring: Bean Validation with @Valid and @Validated
Bean validation with @Valid and @Validated: constraints, custom validators, and handling validation errors in Spring.
Spring Boot
64 articlesBootstrapping a Web Server in Spring Boot
spring-boot-starter-web, @SpringBootApplication, embedded Tomcat, auto-configuration, and running the app.
Application Properties: @Value and @ConfigurationProperties
application.properties vs application.yml, @Value injection, type-safe @ConfigurationProperties, and property overrides.
Building REST APIs with @RestController
@RestController, @GetMapping/@PostMapping, @RequestBody, @PathVariable, @RequestParam, and ResponseEntity.
Global Exception Handling with @ControllerAdvice
@ControllerAdvice, @ExceptionHandler, ProblemDetail (RFC 7807), and consistent error response structure.
Spring Data JPA: Repositories and Entities
@Entity, @Repository, JpaRepository CRUD methods, derived query methods, @Query, and pagination with Pageable.
Actuator: Health Checks and Monitoring
spring-boot-starter-actuator, /actuator/health, /metrics, exposing endpoints, custom health indicators.
Profiles: dev, test and prod Environments
@Profile, spring.profiles.active, profile-specific property files, and activating profiles in tests.
Spring Boot: Security with HTTP Basic & JWT
Spring Security setup: HTTP Basic Auth, custom UserDetailsService, and JWT token generation and validation.
Spring Boot: Testing with @SpringBootTest & MockMvc
Spring Boot testing: @SpringBootTest, @WebMvcTest, MockMvc request/response assertions, and @MockBean.
Spring Boot: Logging with SLF4J & Logback
Spring Boot logging: SLF4J, Logback configuration, log levels, file rolling, and MDC for contextual logging.
Spring Boot: File Upload with MultipartFile
File upload in Spring Boot: MultipartFile handling, saving to disk, validation, multiple files, and file download.
Spring Boot: @Async & Asynchronous Processing
@Async for asynchronous processing: void and CompletableFuture returns, custom thread pool, and exception handling.
Spring Boot: Filters & HandlerInterceptors
Servlet Filters and HandlerInterceptors in Spring Boot: implementation, registration, and use cases like request logging.
Spring Boot: H2 In-Memory Database
H2 in-memory database with Spring Boot: auto-config, H2 console, JPA entities, and schema initialisation.
Spring Boot: Dockerizing a Spring Boot App
Dockerizing Spring Boot: Dockerfile, multi-stage builds, docker-compose with a database, and Buildpacks.
Spring Boot: DevTools & Hot Reload
Spring Boot DevTools: automatic restart on code change, LiveReload, exclusion patterns, and remote DevTools.
Spring Kafka: @KafkaListener
Consuming messages with @KafkaListener: consumer groups, concurrency, manual ack, batch listener, and filtering.
Spring Kafka: KafkaTemplate
Producing messages with KafkaTemplate: sending strings and objects, callbacks, transactions, and custom ProducerFactory.
Spring Kafka: Error Handling & Retry
Spring Kafka error handling: DefaultErrorHandler, backoff retry, @RetryableTopic, and dead letter topic.
Spring WebClient: Reactive HTTP Client
Non-blocking HTTP calls with WebClient: GET, POST, error handling, retry, timeouts, and auth headers.
Spring WebFlux: Reactive REST APIs
Build reactive REST APIs with @RestController using Mono/Flux, functional RouterFunction DSL, R2DBC, and SSE.
Spring Boot OpenAPI 3 & Swagger UI
Auto-generate REST API docs with springdoc-openapi: Swagger UI, @Operation, security schemes, and API groups.
Spring Boot with Redis: Caching & Data Store
RedisTemplate, Spring Cache with @Cacheable, session management, pub/sub messaging, serialization, and Redis Repositories.
Resilience4j: Circuit Breaker, Retry & Rate Limiter
Fault tolerance with Resilience4j: circuit breaker states, retry policies, rate limiting, bulkhead, and fallback strategies.
Spring Boot GraphQL: Schema-First APIs
Build GraphQL APIs with Spring for GraphQL: @QueryMapping, @MutationMapping, DataLoader, subscriptions, and error handling.
Testcontainers: Integration Testing with Real Services
Test with real databases, Kafka, and Redis using Testcontainers: @ServiceConnection, reusable containers, and CI setup.
Spring Kafka: Dead Letter Topics (DLT)
DeadLetterPublishingRecoverer, custom DLT routing, DLT headers and metadata, @DltHandler, and DLT processing strategies.
Spring Kafka: Monitoring & Observability
Micrometer metrics, consumer lag tracking, Prometheus & Grafana dashboards, health indicators, and alerting best practices.
Spring Boot: WebSocket with STOMP
Full-duplex WebSocket communication with STOMP: message broker config, @MessageMapping, SockJS fallback, and user-specific messages.
Spring Boot: Retry with @Retryable
Declarative retry with @Retryable: backoff policies, @Recover fallback, RetryTemplate, and stateful retry for transient failures.
Spring Security: OAuth2 Resource Server & OIDC
JWT bearer token validation, opaque token introspection, Keycloak/Auth0 integration, scope-based authorization, @PreAuthorize method security, and OIDC login.
Spring Batch: Chunk-Oriented Bulk Processing
Job/Step/Chunk architecture, FlatFileItemReader, JdbcBatchItemWriter, ItemProcessor, skip and retry policies, partitioned parallel steps, and scheduling.
Spring Data JPA: Specifications, Projections & N+1 Prevention
Specification API for dynamic queries, interface and DTO projections, @EntityGraph, JOIN FETCH, Hibernate batch fetching, and query performance diagnostics.
Spring Boot Observability: Micrometer, Tracing & Prometheus
Micrometer metrics, custom counters/timers/gauges, @Timed, @Observed, distributed tracing with Zipkin, Prometheus scraping, baggage propagation, and Grafana dashboards.
Multiple DataSources & AbstractRoutingDataSource
Configuring multiple DataSources, separate EntityManagerFactory per datasource, AbstractRoutingDataSource for read/write splitting and multi-tenancy, and transaction pitfalls.
Spring WebFlux: Reactor Operators, Backpressure & Schedulers
flatMap vs concatMap, switchIfEmpty, zip, merge, error recovery with onErrorResume/retry, backpressure strategies, subscribeOn/publishOn, Context propagation, and StepVerifier testing.
Spring Boot Testing Deep Dive: @MockBean, WireMock & Testcontainers
Sliced tests (@WebMvcTest, @DataJpaTest), @MockBean vs @SpyBean, @TestConfiguration, WireMock HTTP stubs, Testcontainers singleton pattern, and context caching best practices.
Spring Boot Native with GraalVM: AOT & Native Hints
Compile Spring Boot apps to native executables: AOT processing, @RegisterReflectionForBinding, RuntimeHintsRegistrar, proxy and resource hints, multi-stage Dockerfile, and native tests.
Spring Integration: Channels, Gateways & Enterprise Patterns
Message channels, @MessagingGateway, @ServiceActivator, @Transformer, @Router, @Splitter/@Aggregator, IntegrationFlow DSL, and channel adapters for File, HTTP, and JMS.
Spring Boot + R2DBC: Reactive Relational Database Access
R2dbcRepository, query derivation, custom @Query, DatabaseClient for complex SQL joins, reactive @Transactional, auditing, pagination, and @DataR2dbcTest with Testcontainers.
Spring Security: Method-Level Security: @PreAuthorize & SpEL
Secure service methods with @PreAuthorize, @PostAuthorize, @PreFilter, @PostFilter and SpEL: role checks, argument inspection, return-value filtering, and custom PermissionEvaluator.
Spring Security: CSRF Protection & CORS Configuration
Configure CSRF and CORS in Spring Security: CookieCsrfTokenRepository for SPAs, disabling CSRF for stateless JWT APIs, global CorsConfigurationSource, and @CrossOrigin.
Spring Security: Custom UserDetailsService & AuthenticationProvider
Custom UserDetails, database-backed UserDetailsService, BCrypt PasswordEncoder, custom AuthenticationProvider for MFA, and wiring multiple authentication sources.
Spring Security: JWT Access & Refresh Token Pattern
Short-lived access tokens, database-backed refresh tokens with rotation and revocation, JWT filter with OncePerRequestFilter, login and refresh endpoints.
Spring Security: ACL: Fine-Grained Object-Level Authorization
Per-object permissions with Spring Security ACL: four-table schema, AclService setup, granting permissions, hasPermission() in @PreAuthorize, and custom permission masks.
Spring Boot: API Versioning Strategies: URI, Header & Content Negotiation
REST API versioning in Spring Boot: URI path versioning, custom X-API-Version header, Accept header content negotiation, custom @ApiVersion annotation with RequestMappingHandlerMapping, and deprecation headers.
Flyway: Database Migrations, Versioned Scripts & Spring Boot Integration
Manage schema evolution with Flyway: versioned SQL scripts, Java-based migrations, callbacks, baseline for existing databases, repair, and Testcontainers integration tests.
Liquibase: Changelogs, Rollbacks & Spring Boot Integration
Database migration with Liquibase: XML and YAML changelogs, first-class rollback support, preconditions, context-based filtering for dev/prod, and Testcontainers testing.
Spring Data JPA: Auditing with @CreatedDate & @LastModifiedBy
Auto-populate audit columns: @EnableJpaAuditing, AuditorAware for current user, @MappedSuperclass base entity, entity listeners, and Hibernate Envers for full revision history.
Spring Data JPA: Soft Delete, Entity Listeners & @EntityGraph
Implement soft delete with @SQLDelete and @SQLRestriction, run lifecycle logic with @PrePersist and @PostLoad, and eliminate N+1 queries with @EntityGraph fetch plans.
Spring Data JPA: Custom Repositories, Querydsl & Specifications
Build dynamic queries with JPA Specifications, type-safe Querydsl predicates, custom repository fragments with EntityManager, interface projections, and DTO projections.
Reactive Security: Spring Security with WebFlux
Secure WebFlux applications: SecurityWebFilterChain, ReactiveUserDetailsService, JWT WebFilter, reactive method security with @PreAuthorize, OAuth2 resource server with JWKS auto-config, and reading the current user reactively.
Spring Cloud Config Server: Centralized Config with Git Backend
Serve configuration to all microservices from a central Git repo: Config Server setup, profile-specific files, live refresh with @RefreshScope, encryption, and securing the server.
Spring Cloud Gateway: Routing, Predicates, Filters & Rate Limiting
Build a production API gateway: route predicates, built-in and custom GatewayFilters, Redis-backed rate limiting, Resilience4j circuit breakers, JWT auth filter, and service-discovery routing.
Spring Cloud OpenFeign: Declarative HTTP Clients & Fallbacks
Replace RestTemplate boilerplate with @FeignClient: request annotations, per-client configuration, RequestInterceptors, ErrorDecoder, circuit breaker fallbacks, and Eureka integration.
Spring Cloud Service Discovery: Eureka Server & Client
Set up Netflix Eureka for service discovery: Eureka Server, client registration, health checks, @LoadBalanced WebClient, self-preservation mode, HA peer replication, and zone-aware routing.
Spring Cloud + OpenTelemetry: Distributed Tracing End-to-End
End-to-end tracing with Micrometer Tracing and OpenTelemetry: automatic W3C propagation, Zipkin and Grafana Tempo backends, custom spans, BaggageField, and MDC log correlation.
Spring Boot on AWS Lambda: Serverless Java with SnapStart
Run Spring Boot serverlessly: Lambda Web Adapter for HTTP routing, Spring Cloud Function for event handlers, SnapStart for sub-second cold starts, SAM CLI local testing, and cold start optimization strategies.
Spring Boot + AWS SQS: Reliable Message Processing with @SqsListener
Consume SQS messages reliably: @SqsListener auto-configuration, batch processing, manual acknowledgement, visibility timeout management, dead letter queues, FIFO ordering, and LocalStack integration tests.
Spring Boot + AWS DynamoDB: NoSQL Data Access with Enhanced Client
Access DynamoDB with the AWS SDK v2 Enhanced Client: @DynamoDbBean entity mapping, CRUD operations, GSI queries, cursor-based pagination, optimistic locking, transactions, and LocalStack testing.
Spring Boot + CRaC: Coordinated Restore at Checkpoint
Near-instant JVM startup with CRaC: checkpoint a warmed-up Spring Boot application and restore in 50–200 ms. Covers resource lifecycle hooks, Spring Boot 3.2 auto-configuration, Docker multi-stage builds, and Kubernetes HPA.
Spring Boot + Kubernetes Operator: Building a Custom Operator in Java
Build a production-grade Kubernetes operator with Java Operator SDK: CRD definition, reconciler control loop, status conditions, dependent resource management, RBAC, and leader election.
Microservices Patterns
4 articlesSaga Pattern: Choreography-Based Distributed Transactions with Kafka
Manage distributed transactions across microservices with the choreography saga pattern: Kafka events, compensating transactions, DLT handling, and best practices for idempotent consumers.
Transactional Outbox Pattern: Reliable Event Publishing with Debezium
Solve the dual-write problem: write events to an outbox table atomically, then relay to Kafka with a polling publisher or Debezium CDC with the Outbox Event Router SMT.
CQRS & Event Sourcing with Spring Boot
Separate read and write models with CQRS: sealed domain events, aggregate reconstitution, append-only event store with optimistic concurrency, and read-model projections with @EventListener.
Idempotency Patterns: Keys, Deduplication & Safe Retries
Build idempotent services: idempotency key header with Redis store, database unique constraints, Kafka consumer deduplication with processed_events table, and HandlerInterceptor for transparent key checking.