Files
spring-boot-demo/README.md
T

32 KiB

spring-boot-demo

Companion code for the Spring Boot articles on ankurm.com.

One directory per article. Each is a self-contained Maven project with its own README.md, numbered documentation chapters under docs/, and captured real output under docs/output/ that a single script regenerates. Every figure quoted in an article came out of one of those files.

Directory Article What it demonstrates
resttemplate-to-restclient/ RestTemplate Is Deprecated in Spring Framework 7.1: Migrate to RestClient (and TestRestTemplate to RestTestClient) the [removal] warnings on 4.2.0 vs none on 4.1.3, every RestTemplate method next to its RestClient call on one real server, exchange() that stops throwing, the RestClient.create(restTemplate) bridge that changes URI encoding, PATCH and User-Agent of each default stack, an interceptor that eats the body, TestRestTemplate vs RestTestClient, and the OpenRewrite recipe's output run for real
email/ Sending Emails in Spring Boot 4: SMTP, HTML Templates, Attachments and Testing the MIME tree of six message shapes (multipart/mixed > related > alternative, and addInline before setText putting the image first), Thymeleaf HTML and TEXT templates ([[...]] still HTML-escapes in TEXT mode), Devanagari subjects as encoded-words and a wrong defaultEncoding turning them into ?, one send per message (5 connections) vs the varargs send (1), @Async returning in milliseconds and a void @Async failure that never reaches the caller, a server that never greets blocking forever until mail.smtp.timeout is set (connectiontimeout does not help), starttls.enable authenticating in plain text while starttls.required refuses, an email still sent when the transaction rolls back unless it waits for AFTER_COMMIT, all against GreenMail on Spring Boot 4.1.2
log4j2-levels/ Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing Levels at Runtime the threshold rule printed as a matrix, a level inherited from the nearest configured ancestor, a logger with its own appender and default additivity printing every line twice, custom DIAG/PERF levels between the standard ones, /actuator/loggers rejecting a custom level and a null reset landing on the root's level instead of the XML's, logging.level.* beating the XML and a custom level in that property stopping the app at startup, argument toString() counts for six call shapes, and Logback plus Log4j2 on one classpath silently handing everything to Logback
idempotency/ Idempotency Keys for POST APIs in Spring Boot (Stripe-Style) with Redis and Postgres one servlet filter and two interchangeable stores: a retried POST after a client timeout creating two payments without a key and one with; 400 / 422 / 409 and replay with Idempotent-Replayed; ten simultaneous duplicates (nine 409 on Redis, nine replays on Postgres because the second INSERT waits on the first's uncommitted row); a crash after the payment commits leaving Redis with a stuck lock and then a duplicate payment, and Postgres with neither; a handler slower than the Redis lock finishing with nothing stored; the legacy Asia/Calcutta zone id that PostgreSQL 16 refuses at connect time
http-service-clients/ Spring Boot 4 HTTP Service Clients: @HttpExchange Interfaces with RestClient (Complete Guide) @HttpExchange interfaces registered with @ImportHttpServices and configured under spring.http.serviceclient.<group>.* (the keys the first version of the post gave are silently ignored), run against a local stub upstream: defaultStatusHandler with ProblemDetail decoding, NotFoundRestClientAdapterDecorator for Optional on a 404, Framework 7 @Retryable on the interface vs RetryTemplate vs an interceptor vs Resilience4j (call counts side by side, and a retried POST created twice), bearer, API-key and OAuth2 client-credentials auth (@ClientRegistrationId ignored without its group configurer), MockRestServiceServer, and the @RestClientTest slice where a group client is not bound to the mock
pdf-invoice/ Generate PDF Invoices in Spring Boot: OpenPDF vs iText vs Flying Saucer (HTML to PDF) one invoice rendered by OpenPDF 3.0.5, iText Core 9.8.0 (AGPL 3 or commercial) and Flying Saucer 10.7.0 from a Thymeleaf template, with embedded Noto Sans Devanagari: none of the three shapes Marathi/Hindi conjuncts by default (checked by rendering to PNG against a libraqm reference), OpenPDF's GlyphLayoutManager does but breaks text extraction until ActualText is on, OpenPDF's static LayoutProcessor is JVM-global and breaks other writers, Apache FOP on the classpath did not help, streamed vs buffered failure (200 + curl exit 18 vs 500), font subsetting, indicative per-invoice timings
filter-interceptor-aop/ Filter vs HandlerInterceptor vs AOP in Spring Boot 4: Which Runs When the real order of a servlet filter, a HandlerInterceptor and an @Aspect printed from a running Tomcat and from MockMvc, the callbacks that still fire (and the ones that do not) after an exception, a 404, a preHandle that returns false and an async request, afterCompletion seeing ex=null after @ControllerAdvice, a header added in postHandle silently lost, a request body read twice, ContentCachingResponseWrapper returning an empty 200, Spring Security 7's chain sitting at order -100, a filter bean running twice, the Framework 7 path-matching removals read with javap, and the three self-invocation-style cases an aspect never sees
excel-export/ Export Excel and CSV from Spring Boot: Streaming 1 Million Rows with Apache POI SXSSF XSSF vs SXSSF under a fixed 512 MB heap (XSSF out of memory between 50,000 and 100,000 rows and at 1,000,000 rows even with 3 GB), 1,000,000 rows streamed with StreamingResponseBody under a 64 MB heap, sheet rolling at 1,048,576 rows, compressTempFiles cutting the spill from 475 MB to 56 MB, OpenCSV swallowing write errors, and an SXSSF file LibreOffice will not open
thymeleaf-htmx/ Spring Boot 4 + Thymeleaf + htmx: Server-Side CRUD UI in 2026 one URL answering as full page or fragment on HX-Request, a Thymeleaf layout, 422 validation re-render, pagination, inline edit and delete, 10 MockMvc tests plus a headless-Chromium check that observed htmx 2 ignoring a 204 and (without a config tag) a 422
rate-limit/ Rate Limiting Spring Boot APIs with Bucket4j and Redis: Per-User, Per-Key and Global Limits per-user, per-API-key and global token buckets in a servlet filter on Bucket4j 8.21 (bucket4j_jdk17-*), 429 with Retry-After and X-RateLimit-* headers, two application instances sharing one Redis bucket and 200 concurrent requests letting exactly 20 through, a limit raised in application.yml that does not change buckets already stored in Redis until a config version is bumped, a client clock 30 s ahead handing out tokens another instance already spent, and fail-open versus fail-closed when Redis dies
sbom/ Spring Boot SBOM in Practice: the tools jar-mode sbom Command, CycloneDX and Dependency Scanning the 4.2.0-RC1 java -Djarmode=tools -jar app.jar sbom command (absent in 4.1.2), the CycloneDX document the build puts in the jar, /actuator/sbom, an SBOM that lists 8 starters not in the jar and misses the jar mode's own library, a licence rule that wrongly flags dual-licensed logback, and an OSV scan that finds Log4Shell in a deliberately old build
hexagonal/ Hexagonal Architecture (Ports and Adapters) in Spring Boot 4 a 4-module Maven reactor that makes "the core has no Spring dependency" something mvn dependency:tree proves rather than a naming convention, testing the core with zero Spring context, and a Spring Boot 4 test-slice-artifact split (@DataJpaTest, @WebMvcTest, TestRestTemplate) hit and fixed along the way
actuator-in-production/ Spring Boot Actuator in Production endpoint exposure defaults, securing Actuator, custom health indicators and how they hang
spring-boot-startup-time/ Why Your Spring Boot App Takes 8 Seconds to Start BufferingApplicationStartup, JFR startup events, self time vs total time, the classpath-scan tax, the JDK 25 AOT cache
configuration-properties/ @ConfigurationProperties vs @Value in Spring Boot 4 relaxed binding measured three ways, record constructor binding, validation, IDE metadata generation
profiles-and-config/ Spring Boot Profiles Done Right the precedence stack made visible, config trees and ConfigMaps, why a profile file loses to an environment variable
spring-aop/ Spring AOP Explained every pointcut designator with real matches, JDK vs CGLIB proxies, six aspects that do not fire
docker-images/ Dockerizing Spring Boot 4: Layered Jars, Buildpacks, Distroless and Image Size Benchmarks one service packaged nine ways and measured: size on disk and pushed, rebuild delta, startup, PID 1 and signals, jlink, the JDK 25 AOT cache
kubernetes-deployment/ Deploying Spring Boot 4 on Kubernetes probe groups under a dependency outage, graceful shutdown under load four ways, JVM ergonomics per pod shape, CPU limits throttling GC, HPA on a Micrometer metric
problem-details/ Global Exception Handling with ProblemDetail (RFC 9457) in Spring Boot 4 thirteen failures under five handling setups, validation errors, i18n, content negotiation, errors outside MVC, silent 500s, decoding on the client
resilience/ Spring Framework 7's Built-in Resilience: @Retryable, @ConcurrencyLimit, and What's Left for Resilience4j @Retryable and @ConcurrencyLimit counted invocation by invocation, retries inside transactions, where Resilience4j still earns its place, migrating from Spring Retry
resilience4j-circuit-breaker/ Resilience4j Circuit Breaker in Spring Boot 4.1: What It's Still For the circuit breaker verified through trip/open/half-open/recover, spring-boot-starter-aop renamed to spring-boot-starter-aspectj (not removed), and where Resilience4j still beats Framework 7's own @Retryable/@ConcurrencyLimit
observability/ A Practical Guide to Monitoring Spring Boot Microservices: Prometheus, Grafana, and Boot 4.1's OpenTelemetry Starter real metrics and traces pushed via OTLP to a real grafana/otel-lgtm container, Docker Compose auto-wiring the endpoint with zero management.otlp.* properties, @Observed silently inert without an explicit ObservedAspect bean, and a dual-version (Boot 4.0 vs 4.1) proof of which OTEL_* environment variables are genuinely new
caching/ The Spring Cache Abstraction: @Cacheable, @CacheEvict, Key Generators and the Self-Invocation Trap the self-invocation trap measured four ways, the key collision SimpleKeyGenerator makes easy, eviction timing under a thrown exception, a rollback the cache keeps, and where this sits next to Hibernate's L2 cache
redis/ Redis with Spring Boot 4.1: RedisTemplate, StringRedisTemplate, @RedisHash, Pub/Sub and TTL the default JDK-serialised RedisTemplate writing keys redis-cli cannot read, before and after Jackson 3 serializers (class names read with javap, the @class allow-list), the six keys two @RedisHash entities create, expired hashes leaving index entries behind unless keyspace events are on, @RedisListener on Boot 4.1's auto-configured container, a plain set clearing a TTL, and a RedisCacheConfiguration bean silently overriding spring.cache.redis.time-to-live
spring-batch/ Spring Batch on Boot 4.1: Jobs, Steps, Chunk Processing and Restartability a job that fails mid-chunk and resumes exactly where it left off across two separate JVMs, skip vs. restart on the same poisoned row, the resourceless job repository that forgets a restart ever happened, and the chunk(int) vs chunk(int, tx) builder split
spring-batch-partitioning/ Spring Batch Partitioning and Parallel Steps: Scaling a 10-Million-Row Job the real grid-size sweep at 10M and 300K rows (best speedup 1.42x, on 2 cores), MultiResourcePartitioner ignoring gridSize entirely, a rejected partition's StepExecution stuck at STARTING forever, and Spring Batch 6.0's new JobOperator#recover unsticking it
db-migrations-flyway-liquibase/ Flyway vs Liquibase for Spring Boot 4: Migrations, Rollbacks and Baselines Flyway Community's undo throwing FlywayRedgateEditionRequiredException at runtime, a real Liquibase 5.0.3 filename-caching defect that produces a phantom successful run, Liquibase's 10-second default lock-poll rate versus Flyway's near-instant row lock, the FSL license change and its ASF/Keycloak fallout, and what actually happens when both tools are enabled against one database
db-migrations-expand-contract/ Zero-Downtime Database Migrations: Expand-Contract in Practice with Spring Boot a real 4-deploy rolling sequence against two live replicas with a load generator proving 99.98% success, H2's AUTO_SERVER single-point-of-failure trap, a NOT NULL constraint that fails every Stage 4 insert, and ALTER TABLE silently dropping a concurrently committed row with no exception thrown
openapi-versioning/ springdoc-openapi with Spring Boot 4.1: Generating, Customising and Versioning Your API Spec springdoc 3.1.1 silently merging same-path, different-version handlers into one oneOf operation with an arbitrary operationId, a working per-version fix with GroupedOpenApi + OpenApiCustomizer, and the officially-versioning-supported functional-endpoint path turning out to document only one of two registered versions
graphql-dataloader/ Spring GraphQL 2.0: Schema-First APIs, DataLoader Batching and Killing N+1 a naive @SchemaMapping resolver measured at 21 SQL statements for 20 books versus a @BatchMapping resolver's flat 2, a dangling foreign key nulling an entire GraphQL response via non-null propagation identically under both resolver strategies, and two Spring Boot 4.1 packaging changes (DataSourceAutoConfiguration's new package, Jackson 3 by default) hit along the way
custom-validation/ Custom Validation in Spring Boot: Beyond the Basics! the javax.validation to jakarta.validation namespace fix Boot 3 already required, Jakarta Validation 3.1's record-validation clarification proven on both field- and class-level custom constraints, a record validation failure's empty 400 body by default, and what spring.mvc.problemdetails.enabled does and does not fix
etag-caching/ Mastering Cache Control with ETag in Spring Boot RESTful APIs spring-boot-starter-web's own POM now reading "deprecated in favor of spring-boot-starter-webmvc", ShallowEtagHeaderFilter and WebRequest.checkNotModified() re-verified unchanged on Spring Framework 7, deep cache vs shallow cache, and conditional PUT with If-Match as optimistic locking
restclient-basic-auth/ Spring Boot RestTemplate with Basic Auth: A Modern Guide RestClient with Basic Auth two ways against a real embedded server, {noop} passwords confirmed to emit no runtime warning at all, spring-boot-starter-restclient as its own required Boot 4 module, and the RestClient.exchange() trap covered in depth by the RestTemplate to RestClient migration guide
core-di/ Dependency Injection in Spring Boot 4: Constructor vs Setter vs Field (and Why Field Injection Hurts) and @Autowired Explained: By-Type Resolution, @Qualifier, @Primary, ObjectProvider and List Injection one OrderService in three injection styles built with plain new, a field-injected dependency used in a constructor, circular dependencies in plain Spring vs Boot with the real failure report, @Lazy injecting a proxy, and the @Autowired resolution ladder read from Spring 7.0.9 bytecode (name match beats @Priority), plus the empty-collection trap that only bites field and setter injection
core-beans/ Spring Bean Scopes: Singleton, Prototype, Request, Session and the Prototype-in-Singleton Trap Spring Bean Lifecycle in Boot 4: @PostConstruct, InitializingBean, SmartLifecycle and Shutdown Order and Circular Dependencies in Spring Boot 4: Why Startup Fails and 4 Ways to Fix It instance counts per scope, five fixes for a prototype inside a singleton, request scope without a proxy failing at start-up, every lifecycle callback in order, @PostConstruct running before the proxy exists, SmartLifecycle phases measured, a SmartLifecycle at the default phase stopping before Tomcat has drained, and the circular-dependency start-up failure reproduced with four fixes
custom-starter/ Write Your Own Spring Boot 4 Starter: Auto-Configuration, @Conditional and Properties a starter split into an auto-configuration module and a starter, the AutoConfiguration.imports registration, @ConditionalOn* conditions, configuration metadata, and tests with ApplicationContextRunner
core-events/ Spring Application Events: @EventListener, @TransactionalEventListener and Async Events publishing and consuming events, listener ordering, conditional listeners, AFTER_COMMIT behaviour proven with a rollback, and async listeners
multi-datasource/ Multiple DataSources in Spring Boot 4 with Spring Data JPA two H2 databases each with its own DataSource, Flyway, EntityManagerFactory and transaction manager, six ways of getting the wiring wrong, plain vs named @Transactional, and ChainedTransactionManager under a failing commit
i18n/ Internationalization (i18n) in Spring Boot 4: MessageSource, LocaleResolver and Localized ProblemDetail English, Marathi and Hindi message bundles, Accept-Language vs a cookie resolver, apostrophes and Devanagari digits in MessageFormat, the JVM default locale as a hidden fallback, localized validation messages and ProblemDetail titles
aot-cache/ Faster Spring Boot Startup with the JDK AOT Cache (JEP 514/515): Benchmarks vs CDS and Native the JDK 25 AOT cache trained two ways, against a plain JVM, AppCDS, Spring's own AOT output and a GraalVM native image (ten interleaved rounds each), first-request latency, 24 cases where the cache silently stops applying (jar, timestamp, JVM build, ZGC, compact headers), -XX:AOTMode=on, Docker layer arithmetic
kotlin/ Kotlin with Spring Boot 4.1: Null Safety, Coroutines, and What Java Developers Get Wrong Kotlin 2.3.21 (Boot 4.1.1's own managed version, not the latest GA), the real @Configuration class may not be final and @Bean method must not be private or final failures without the allopen/noarg spring/jpa compiler plugins, suspend fun/Flow<T> controller methods proven to still resume off a Tomcat thread under plain spring-boot-starter-webmvc, a JSpecify @NullMarked Java method that still NPEs at runtime because the contract isn't runtime-checked, and TestRestTemplate confirmed absent from Boot 4.1's spring-boot-test jar
testing-no-containers/ Testing Spring Boot 4 Without Containers: WireMock, MockWebServer and @MockitoBean @MockBean's total removal proven with a real javac failure, @MockitoBean/@MockitoSpyBean context-cache behavior proven with real org.springframework.test.context.cache DEBUG log lines, WireMock fault injection against a real RestClient, a real NoClassDefFoundError from mixing wiremock with wiremock-jetty12 (fixed with wiremock-standalone), and MockWebServer's SocketEffect.ShutdownConnection for genuinely severing a connection mid-response
rest-test-client/ RestTestClient in Spring Framework 7: Testing REST APIs End-to-End (vs MockMvcTester) one fluent RestTestClient API proven across bindToController, bindTo(mockMvc), bindToApplicationContext and bindToServer; RestTestClient, TestRestTemplate and @WebMvcTest confirmed relocated into new Spring Boot 4 modules by unzipping the real jars; two distinct real failures for the two now-separate @AutoConfigureRestTestClient/@AutoConfigureTestRestTemplate annotations; and the JDK HttpClient Boot picks for bindToServer caught transparently decoding gzip and hiding Content-Encoding, verified against curl and against the older SimpleClientHttpRequestFactory
file-transfer/ File Upload and Download in Spring Boot 4: Multipart, Streaming and S3 Presigned URLs multipart limits enforced by Tomcat (and ignored by MockMvc), the client-controlled filename, Range downloads, a 200 MB download and 150 MB upload under -Xmx64m, and S3 presigned URLs checked against a local SigV4 verifier (not a real S3)
project-structure/ Spring Boot Project Structure: Package-by-Layer vs Package-by-Feature the same application written package-by-layer and package-by-feature with one HTTP API, the real source trees, 9 of 9 types public by layer vs 3 of 15 by feature, and the javac error that makes a feature boundary a compiler rule instead of a convention
crud-mysql/ Spring Boot CRUD REST API with MySQL and Spring Data JPA a complete book API on a real MySQL 8.4.6 server with Flyway owning the schema and Hibernate set to validate, ProblemDetail errors with per-field validation messages, a duplicate ISBN caught by the database's unique key and mapped to 409 on create and on update, MySQL's own Duplicate entry message, and the SQL behind every request
boot42-rc1-checklist/ Spring Framework 7.1 and Spring Boot 4.2: What's Coming and How to Prepare superseded by boot42-upgrade/; kept because older posts link to it. Each 4.2 milestone change run on 4.2.0-RC1 and on 4.1.2: @DefaultValue placeholders resolved, five new Kafka admin keys that 4.1.2 silently ignores, embedded LDAP SSL failing without a bundle, the properties migrator's real report (and the removed key it misses), and the RestTemplate removal warnings from the compiler
boot42-upgrade/ Spring Boot 4.2 GA: What's New, What's Deprecated and the 4.1 to 4.2 Upgrade Checklist the 4.2.0 GA re-run of the RC1 checklist against 4.1.3: @DefaultValue placeholders, Kafka admin keys that 4.1.3 silently ignores, embedded LDAP SSL without a bundle, SSL-bundle options rejected by the LDAP client, the migrator's real report and its new spring.properties.migrator.fail switch, compiler [removal] warnings for RestTemplate, TestRestTemplate and the Pulsar classes, open-telemetry convention now starting, plus defaults, buildpack builder constants and BOM versions read straight from the 4.1.3 and 4.2.0 artifacts
boot42-otel/ Spring Boot 4.2 OpenTelemetry: Semantic Conventions, Shared OTLP Settings and MDC Keys one request measured under each management.observations.conventions value (the documented open-telemetry fails to start on RC1, opentelemetry works), meter, span and Prometheus names before and after, management.opentelemetry.otlp.* verified against a local OTLP receiver (paths, merged headers, gzip, per-signal overrides), custom MDC keys, and the LongTaskTimer that is no longer on by default
boot4-migration/ Spring Boot 3 to 4 Migration Guide (Updated for 4.1 and 4.2) one Boot 3.5.16 service migrated to 4.1.2 with the real failures captured at each step: 12 javac errors from a version bump, a start-up failure from a missing spring-boot-starter-restclient, Flyway silently not running without spring-boot-starter-flyway, removed logging.file.* keys silently ignored, Jackson 3 sorting bean properties, liveness/readiness groups appearing, and a @Mock field that is null without MockitoExtension
startup-runners/ CommandLineRunner vs ApplicationRunner vs ApplicationReadyEvent in Spring Boot 4 the real order of every startup hook printed from a running app, one shared sort for both runner types with arbitrary ties, runner failure vs ApplicationReadyEvent listener failure (exit codes, ApplicationFailedEvent), a blocking runner holding readiness at 503, SmartLifecycle phases, and which hooks @SpringBootTest and @WebMvcTest run
mapstruct/ MapStruct with Spring Boot 4 and Java Records: DTO Mapping Done Right records as source and target, nested and collection mapping, null strategies, @AfterMapping and @DecoratedWith, real compile-time error text for broken mappers, three ways to test a mapper, and an indicative comparison with hand-written code and Dozer
secrets/ Secrets in Spring Boot: Vault vs AWS Secrets Manager vs Kubernetes Secrets vs Jasypt spring.config.import against a real Vault 2.2.1 (Spring Cloud Vault 5.0.3 on Boot 4.1.2): a missing path, a wrong token and an unreachable Vault all start the app with db.password unset unless spring.cloud.vault.fail-fast=true (and a missing path even then); a rotation in Vault invisible until ContextRefresher.refresh(), which updates the Environment and a @RefreshScope bean but not a record-bound @ConfigurationProperties; a least-privilege token; AWS Secrets Manager (Spring Cloud AWS 4.2.1, run against the moto emulator, not AWS) where a missing secret fails startup but optional: hides it and the 1 s polling reload never fired; Kubernetes Secrets as a kubelet-layout config tree that keeps its old value after the volume swap until a refresh; Jasypt 4.0.4 ENC(...) decrypted by anyone holding the ciphertext and the key; actuator show-values=ALWAYS; secrets in the jar, in ps and in /proc/<pid>/environ; and @DynamicPropertySource arriving after the Vault import

core-di, core-beans, custom-starter, core-events, multi-datasource, i18n, aot-cache, kotlin, testing-no-containers, rest-test-client and hexagonal are the exception: they have no docs/NN-topic.md chapter folder. Their deeper material lives in collapsible sections inside the articles themselves. Where their captured output sits is not uniform, and is worth checking per module rather than assuming: core-di, core-beans, custom-starter, core-events, multi-datasource, i18n and aot-cache keep it in a top-level output/ directory (hexagonal is also the one multi-module reactor in this repo, so its output sits one level deeper still, under each module: core/output/, persistence-adapter/output/, and so on) — but kotlin, testing-no-containers and rest-test-client still use docs/output/, same as the chaptered modules, just without the docs/NN-topic.md chapters themselves.

Articles whose text is kept here rather than only on the blog have it under <directory>/post/ — post.md for the body and meta.md for the title, excerpt and categories.

Running any of them

Each project needs a JDK 25 and Maven 3.9. redis and rate-limit also need redis-server and redis-cli on the PATH. docker-images, observability and secrets also need Docker, and kubernetes-deployment Docker plus a Kubernetes cluster; their READMEs list the rest:

cd <directory>
export JAVA_HOME=/path/to/jdk-25
mvn -DskipTests package
./scripts/run-all.sh          # regenerate every transcript under docs/output/

Licence

MIT — see LICENSE.