Tutorial

264 posts in this section

Setting Up Spring Boot with Spring Data JPA and MySQL

Introduction This article builds the project foundation used throughout the entire series. By the end, you will have a running Spring Boot 3.3 application connected to MySQL 8.x with Hibernate 6, a proper connection pool, schema management via Flyway, and SQL logging configured so you can see exactly what Hibernate sends to the database. Project Setup Maven pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.

Continue reading »

Specifications and the Criteria API: Dynamic Queries

Why Specifications Derived query methods and @Query annotations work for fixed queries. But what happens when the user can filter by any combination of 10 fields — some optional, some not? // Wrong approach — combinatorial explosion List<Product> findByName(String name); List<Product> findByNameAndPrice(String name, BigDecimal price); List<Product> findByNameAndPriceAndCategory(...); // ... you'd need 2^10 = 1024 methods The Specification pattern solves this. Each filter condition is a reusable Specification<T> object. You compose them with and(), or(), and not() at runtime, and Spring Data JPA generates the correct query.

Continue reading »

Spring Authorization Server: Build Your Own OAuth2 Server

What Is Spring Authorization Server? Spring Authorization Server (SAS) is an official Spring project that implements OAuth 2.1 and OpenID Connect 1.0 as a Spring Boot application. It provides a complete authorization server you can host yourself — issuing tokens for your own clients and APIs. Use it when: You want SSO across your own microservices You cannot use a hosted provider (Okta, Auth0) due to compliance or cost You need complete control over token format and claims You’re building a platform where other apps authenticate against your identity service Architecture flowchart TD SPA[SPA / Mobile App\nOAuth2 Client] -->|Authorization Code + PKCE| SAS Service[Backend Service\nClient Credentials| SAS] SAS[Spring Authorization Server\nIssues tokens] RS1[Your REST API\nResource Server] -->|Validates JWT| SAS RS2[Another API\nResource Server] -->|Validates JWT| SAS SAS -->|Signs tokens with| PK[Private Key\nJWK Set at /.

Continue reading »

Spring Kafka Production Checklist and Best Practices

Before You Ship This is the checklist distilled from everything in this series. Work through it before your first production deployment. Each item links to the article where it’s covered in depth. Producer Checklist Durability # Never lose data on leader failure spring.kafka.producer.acks=all # At least 2 brokers must acknowledge every write spring.kafka.producer.properties.min.insync.replicas=2 # Enables exactly-once message delivery (required for transactions) spring.kafka.producer.properties.enable.idempotence=true Do: Set acks=all and min.insync.replicas=2 for any topic that carries business data.

Continue reading »

Spring Security Best Practices and Production Checklist

Using This Reference This is the final article in the Spring Security series. It is a consolidated reference — not a tutorial. Come back to this checklist before every launch and when reviewing a new codebase. Each item links back to the relevant article in the series. 1. Keep Spring Security Updated Security vulnerabilities in Spring Security itself are rare but severe when they occur. A dependency that is one minor version behind can expose known CVEs.

Continue reading »

Starting a Kafka Cluster: Single-Broker and 3-Broker with KRaft

Prerequisites Docker Desktop installed and running docker compose v2 (bundled with Docker Desktop 4.x+) Ports 9092, 9093, 9094 free on your machine All articles in this series assume a running local Kafka cluster. Start with the single-broker setup for articles 1–6, then switch to the 3-broker cluster when we cover replication and fault tolerance. Single-Broker Cluster (Development) This is the simplest setup — one Kafka node running in combined mode (broker + controller).

Continue reading »

Structured Concurrency (JEP 453): Safe, Readable Concurrent Code

Preview Feature — Requires --enable-preview at compile and runtime. The API stabilized significantly from Java 21 through 24 and will be finalized in a future release. The Unstructured Concurrency Problem When you submit tasks to an ExecutorService, the tasks are logically related but structurally unconnected — the executor doesn’t know they belong together: // Unstructured concurrency — looks simple, hides serious problems ExecutorService executor = Executors.newCachedThreadPool(); Future<Order> orderFuture = executor.

Continue reading »

Switch Expressions (JEP 361): Switch as an Expression, Not Just a Statement

Finalized in Java 14 (JEP 361). Available in all Java 14+ releases, including Java 17. Previous previews: Java 12 (JEP 325) and Java 13 (JEP 354). The Problem with Switch Statements Java’s traditional switch statement has two well-known pain points: Pain 1: Fall-Through // Java 11 — easy to introduce fall-through bugs switch (day) { case MONDAY: result = "Start of work week"; break; // easy to forget this case TUESDAY: result = "Weekday"; // no break — falls through to WEDNESDAY case case WEDNESDAY: result = "Hump day"; break; default: result = "Other"; } A missing break causes the next case to execute unexpectedly.

Continue reading »

Testing Kafka Applications: EmbeddedKafka and Testcontainers

Two Testing Strategies Strategy Speed Fidelity Use when @EmbeddedKafka Fast (~2s startup) In-process broker, not 100% identical Unit/integration tests — CI fast path KafkaContainer (Testcontainers) Slower (~10s startup) Real Kafka broker in Docker Acceptance tests, DLT/transaction validation Use both: @EmbeddedKafka for the bulk of tests, KafkaContainer for the smoke suite that validates real-broker behaviour. Test Dependencies <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>kafka</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <scope>test</scope> </dependency> @EmbeddedKafka — Fast Integration Tests Testing a Producer @SpringBootTest @EmbeddedKafka( partitions = 1, topics = {"orders"}, brokerProperties = {"log.

Continue reading »

Testing Spring Data JPA: @DataJpaTest, Testcontainers, and Best Practices

Why Test JPA Code? Unit tests with mocked repositories verify your service logic but nothing about the database. They won’t catch: Wrong column mapping Constraint violations N+1 queries introduced by a new lazy association Transactions that silently don’t roll back Queries that fail on the real database but pass on H2 Testing against a real database — or at minimum a database-compatible in-memory store — is necessary. Spring Boot’s @DataJpaTest and Testcontainers make this practical.

Continue reading »