Java

223 posts in this section

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 »

Stream & Optional API Enhancements (Java 9–11)

Stream API — New Methods (Java 9) Java 9 added four new instance methods to Stream<T>. All are terminal-ish or intermediate operations that make common patterns expressible without workarounds. takeWhile(Predicate) Returns elements from the beginning of the stream as long as the predicate holds, then stops. The first element that fails the predicate (and all subsequent elements) are discarded. Stream.of(1, 2, 3, 4, 5, 1, 2) .takeWhile(n -> n < 4) .

Continue reading »

Streams API: Lazy Pipelines and the Functional Data Model

The Problem Streams Solve Java loops are not wrong — they are often the right tool. But when a computation is a multi-step pipeline of filter → transform → aggregate, a loop hides the structure of the computation in a tangle of temporary variables and mutated collections. The Streams API makes the structure explicit, lets the JVM optimise it, and composes naturally with lambdas and method references. Consider filtering a list of orders to find the names of active premium customers who spent over $500, sorted alphabetically:

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 »