{"version":"https://jsonfeed.org/version/1.1","title":"JavaHacks","home_page_url":"https://javahacks.dev","feed_url":"https://javahacks.dev/feed.json","description":"Practical guides and hacks for Java developers","language":"en","authors":[{"name":"JavaHacks","url":"https://javahacks.dev"}],"items":[{"id":"https://javahacks.dev/library/modern-java-guide-language","url":"https://javahacks.dev/library/modern-java-guide-language","title":"Modern Java Guide to Records Sealed Types and Patterns","summary":"Write idiomatic Java 25 with records, sealed types, pattern matching, streams and virtual threads, and learn which old habits to drop first.","content_html":"<p>Most Java code in production was written for Java 8, and it shows: getters and setters on every class, <code>instanceof</code> followed by a cast, a visitor with six methods to avoid a type check. Since Java 16 the language has a better answer to each of those, and Java 25, the long-term support release that followed Java 21, finalizes the last pieces you need to write in the new style every day. This guide builds one small payment model on Java 25 and uses it to cover the features worth knowing, in the order you will reach for them. The version floor for each feature is in the sentence that depends on it.</p>\n<p>If your project is on Spring, the same style carries over: <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a> uses records for configuration and DTOs from the first page.</p>\n<h2>Model values with records</h2>\n<p>A record declares its components once and the compiler generates the constructor, accessors, <code>equals</code>, <code>hashCode</code> and <code>toString</code>. Records arrived as final in Java 16 (<a href=\"https://openjdk.org/jeps/395\">JEP 395</a>).</p>\n<pre data-filename=\"Money.java\"><code class=\"language-java\">public record Money(long cents, String currency) {\n\n    public Money {\n        if (cents &lt; 0) {\n            throw new IllegalArgumentException(\"cents must not be negative: \" + cents);\n        }\n        currency = currency.toUpperCase();\n    }\n\n    public Money plus(Money other) {\n        if (!currency.equals(other.currency)) {\n            throw new IllegalArgumentException(\"currency mismatch\");\n        }\n        return new Money(cents + other.cents, currency);\n    }\n}</code></pre>\n<p>The block without parentheses is a compact constructor. It runs before the fields are assigned, so you validate and normalize the parameters there. Assigning to <code>currency</code> changes the parameter, and the field receives the normalized value.</p>\n<p>A record is shallowly immutable. The fields cannot be reassigned, but a <code>List</code> component is still a mutable list unless you copy it in the compact constructor with <code>List.copyOf()</code>. That one line is the most common thing people forget.</p>\n<p>Use a record for values that are defined by their contents: money, coordinates, an API response. Do not use one for a JPA entity. Hibernate needs a no-argument constructor and mutable state for proxies, and a record has neither (<a href=\"/library/hibernate-jpa-guide-without-surprises\">the Hibernate guide</a> covers what to use instead).</p>\n<h2>Close hierarchies with sealed types</h2>\n<p>A sealed type lists every class allowed to implement it. Sealed classes became final in Java 17 (<a href=\"https://openjdk.org/jeps/409\">JEP 409</a>).</p>\n<pre data-filename=\"PaymentMethod.java\"><code class=\"language-java\">public sealed interface PaymentMethod permits Card, BankTransfer, Voucher {}\n\nrecord Card(String last4, int expiryYear) implements PaymentMethod {}\nrecord BankTransfer(String iban) implements PaymentMethod {}\nrecord Voucher(String code, long cents) implements PaymentMethod {}</code></pre>\n<p>The three records can sit in the same file as the interface, so the compiler can see the whole hierarchy. That is what makes the next step safe.</p>\n<h2>Branch with pattern matching</h2>\n<p>Pattern matching for <code>switch</code> and record patterns are final since Java 21 (<a href=\"https://openjdk.org/jeps/441\">JEP 441</a> and <a href=\"https://openjdk.org/jeps/440\">JEP 440</a>). A <code>switch</code> over a sealed type needs no <code>default</code>, and adding a fourth payment method breaks the build at every <code>switch</code> that forgot it.</p>\n<pre data-filename=\"Describe.java\"><code class=\"language-java\">static String describe(PaymentMethod method) {\n    return switch (method) {\n        case Card(String last4, int year) when year &lt; 2026 -&gt; \"expired card ending \" + last4;\n        case Card(String last4, int year) -&gt; \"card ending \" + last4;\n        case BankTransfer(String iban) -&gt; \"transfer from \" + iban.substring(0, 4);\n        case Voucher(String code, long cents) -&gt; \"voucher %s worth %d cents\".formatted(code, cents);\n    };\n}</code></pre>\n<p>Calling <code>describe(new Card(\"4242\", 2030))</code> returns <code>card ending 4242</code>. The guarded case must come before the unguarded one for the same type, or the compiler rejects the second as dominated.</p>\n<p>The old way was a chain of <code>instanceof</code> checks with casts, or a visitor. The visitor is still right when the hierarchy is open and the operations are closed. A sealed hierarchy flips that: the set of types is fixed and the operations multiply, which is exactly where a <code>switch</code> wins.</p>\n<h2>Use var where the type is already visible</h2>\n<p><code>var</code> has been in the language since Java 10 and only changes what you type, not how the variable is typed.</p>\n<pre><code class=\"language-java\">var orders = new ArrayList&lt;Order&gt;();\nvar total = orders.stream().mapToLong(Order::cents).sum();</code></pre>\n<p>The first line is clearer with <code>var</code> because <code>new ArrayList&lt;Order&gt;()</code> says it all. The second is borderline: a reader has to know <code>sum()</code> on a <code>LongStream</code> returns <code>long</code>. When the right-hand side hides the type, write the type.</p>\n<h2>Streams for transformations, loops for control flow</h2>\n<p>Streams express a pipeline of transformations. A loop with early exit, mutation or checked exceptions is usually clearer as a loop. A grouped total shows where a stream is the better tool:</p>\n<pre data-filename=\"Totals.java\"><code class=\"language-java\">record Order(String customer, String sku, int quantity, long cents) {}\n\nvar orders = List.of(\n    new Order(\"ana\", \"A-1\", 2, 1_500),\n    new Order(\"ana\", \"B-2\", 1, 4_000),\n    new Order(\"ben\", \"A-1\", 5, 1_500));\n\nMap&lt;String, Long&gt; totals = orders.stream().collect(\n    Collectors.groupingBy(Order::customer, TreeMap::new,\n        Collectors.summingLong(o -&gt; o.quantity() * o.cents())));\n\nSystem.out.println(totals);</code></pre>\n<pre><code class=\"language-text\">{ana=7000, ben=7500}</code></pre>\n<p><code>Stream.toList()</code>, added in Java 16, returns an unmodifiable list and allows <code>null</code> elements. <code>Collectors.toList()</code> makes no promise about mutability. Pick the first unless a caller needs to add to the result. If you meet the exception that follows from getting this wrong, <a href=\"/library/unsupportedoperationexception-fix-immutable-lists\">UnsupportedOperationException on immutable lists</a> walks through it.</p>\n<h2>Text blocks and the small API upgrades</h2>\n<p>A text block (final in Java 15) is a multi-line string literal that strips the common indentation, which makes embedded SQL and JSON readable:</p>\n<pre><code class=\"language-java\">String sql = \"\"\"\n    SELECT id, name\n    FROM customers\n    WHERE active = true\n    ORDER BY name\n    \"\"\";</code></pre>\n<p>Other additions you will use constantly: <code>List.of()</code> and <code>Map.of()</code> for immutable collections (Java 9), <code>String.isBlank()</code>, <code>strip()</code> and <code>repeat()</code> (Java 11), <code>formatted()</code> (Java 15), and sequenced collections in Java 21, which add <code>getFirst()</code>, <code>getLast()</code> and <code>reversed()</code> to <code>List</code>, <code>Deque</code> and <code>LinkedHashSet</code>.</p>\n<h2>Threads that do not cost a thread</h2>\n<p>Virtual threads are final since Java 21 (<a href=\"https://openjdk.org/jeps/444\">JEP 444</a>). A virtual thread is scheduled by the JVM on a small pool of carrier threads, and it unmounts while blocked on I/O, so one thread per request stops being a scaling problem.</p>\n<pre><code class=\"language-java\">try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {\n    for (int i = 0; i &lt; 1_000; i++) {\n        int id = i;\n        executor.submit(() -&gt; fetchProfile(id));\n    }\n}</code></pre>\n<p>The <code>try</code> block waits for every submitted task on close. Do not pool virtual threads, because they are cheap to create and pooling them defeats the point. Code that spends its time computing gains nothing from them, since the number of carrier threads is bound to your cores. The <a href=\"/library/java-threads-tutorial-explained-thread-executorservice\">thread basics post</a> explains the platform thread model they replace.</p>\n<h2>What Java 25 adds to day-to-day code</h2>\n<p>Java 25 is a long-term support release. Three of its finalized features change what a small program looks like:</p>\n<ul><li>Compact source files and instance <code>main</code> methods (<a href=\"https://openjdk.org/jeps/512\">JEP 512</a>) let a script or a lesson start without a class declaration or <code>static</code>.</li><li>Module import declarations (<a href=\"https://openjdk.org/jeps/511\">JEP 511</a>) allow <code>import module java.base;</code> to bring in a whole module's exported packages.</li><li>Flexible constructor bodies (<a href=\"https://openjdk.org/jeps/513\">JEP 513</a>) let you validate arguments before calling <code>super(...)</code> or <code>this(...)</code>.</li></ul>\n<p>None of these should push you to upgrade by itself. The reason to move from 21 to 25 is the support window and the runtime improvements, and the language additions are a bonus. How the runtime turns bytecode into machine code is covered in <a href=\"/library/jvm-works-bytecode-machine-code\">how the JVM works</a>.</p>\n<h2>Habits to drop</h2>\n<table><thead><tr><th>Old habit</th><th>Modern replacement</th><th>Since</th></tr></thead><tbody><tr><td>Class with getters, <code>equals</code> and <code>hashCode</code> for plain data</td><td><code>record</code></td><td>Java 16</td></tr><tr><td><code>instanceof</code> plus cast</td><td><code>if (o instanceof Card c)</code></td><td>Java 16</td></tr><tr><td>Visitor over a closed set of types</td><td><code>sealed</code> plus <code>switch</code> patterns</td><td>Java 21</td></tr><tr><td>String concatenation for multi-line text</td><td>Text block</td><td>Java 15</td></tr><tr><td><code>Collectors.toList()</code> for a read-only result</td><td><code>Stream.toList()</code></td><td>Java 16</td></tr><tr><td>Thread pool sized for blocking I/O</td><td>Virtual threads</td><td>Java 21</td></tr></tbody></table>\n<h2>Records in daily use</h2>\n<p>The money example shows the mechanics. Real code uses records in a few recurring ways, and the habits are worth learning together. A record can implement an interface, which lets a value type take part in a hierarchy without a base class. It can have static factory methods, which name the construction paths that a bare constructor cannot, and instance methods for derived values:</p>\n<pre><code class=\"language-java\">public record DateRange(LocalDate start, LocalDate end) implements Comparable&lt;DateRange&gt; {\n\n    public DateRange {\n        Objects.requireNonNull(start, \"start\");\n        Objects.requireNonNull(end, \"end\");\n        if (end.isBefore(start)) {\n            throw new IllegalArgumentException(\"end \" + end + \" is before start \" + start);\n        }\n    }\n\n    public static DateRange ofDays(LocalDate start, int days) {\n        return new DateRange(start, start.plusDays(days));\n    }\n\n    public long days() {\n        return ChronoUnit.DAYS.between(start, end);\n    }\n\n    public boolean overlaps(DateRange other) {\n        return start.isBefore(other.end) &amp;&amp; other.start.isBefore(end);\n    }\n\n    @Override\n    public int compareTo(DateRange other) {\n        return start.compareTo(other.start);\n    }\n}</code></pre>\n<p>Because the equality of a record follows its components, a <code>DateRange</code> works as a key in a <code>Map</code> and as an element of a <code>Set</code> with no extra code. Records have no setters, so a change produces a new instance. A small \"with\" method keeps that readable, and it is better than a builder for records of a handful of components:</p>\n<pre><code class=\"language-java\">public record Address(String street, String city, String postalCode) {\n\n    public Address withCity(String newCity) {\n        return new Address(street, newCity, postalCode);\n    }\n}</code></pre>\n<p>Nested records are natural for a request or a response. The shape is visible at a glance and each level is validated on its own:</p>\n<pre><code class=\"language-java\">public record CreateOrder(String customerId, List&lt;Line&gt; lines, Address shipTo) {\n\n    public record Line(String sku, int quantity) {\n        public Line {\n            if (quantity &lt;= 0) throw new IllegalArgumentException(\"quantity must be positive\");\n        }\n    }\n\n    public CreateOrder {\n        lines = List.copyOf(lines);               // defensive copy, and rejects nulls\n        if (lines.isEmpty()) throw new IllegalArgumentException(\"an order needs at least one line\");\n    }\n}</code></pre>\n<p>Two limits are worth knowing before you adopt records everywhere. A record cannot extend another class, and its fields are final, so it is the wrong fit for anything that a framework must proxy or mutate. And the generated <code>toString</code> prints every component, so a record with a password or a token will print it in a log line unless you override the method. Keep secrets out of records, or override <code>toString</code>.</p>\n<h2>Pattern matching in the small</h2>\n<p>The big feature is the <code>switch</code>, and the small one is <code>instanceof</code> with a binding, which removes a cast and a variable. The binding is in scope where the compiler can prove the test passed, and that includes the right side of <code>&amp;&amp;</code>:</p>\n<pre><code class=\"language-java\">if (shape instanceof Circle c &amp;&amp; c.radius() &gt; 10) {\n    return \"large circle\";\n}\n\nif (!(value instanceof String text)) {\n    throw new IllegalArgumentException(\"expected a string but got \" + value);\n}\nreturn text.strip();                          // text is in scope here, after the early exit</code></pre>\n<p>Record patterns deconstruct a value in the pattern and nest, so a method over a small tree reads like the data it handles:</p>\n<pre><code class=\"language-java\">sealed interface Expr permits Num, Add, Mul, Neg {}\nrecord Num(double value) implements Expr {}\nrecord Add(Expr left, Expr right) implements Expr {}\nrecord Mul(Expr left, Expr right) implements Expr {}\nrecord Neg(Expr operand) implements Expr {}\n\nstatic double evaluate(Expr expr) {\n    return switch (expr) {\n        case Num(double value) -&gt; value;\n        case Add(Expr left, Expr right) -&gt; evaluate(left) + evaluate(right);\n        case Mul(Expr left, Expr right) -&gt; evaluate(left) * evaluate(right);\n        case Neg(Expr operand) -&gt; -evaluate(operand);\n    };\n}\n\nstatic String show(Expr expr) {\n    return switch (expr) {\n        case Num(var v) -&gt; String.valueOf(v);\n        case Add(Num(var a), Num(var b)) -&gt; a + \" + \" + b;\n        case Add(var l, var r) -&gt; \"(\" + show(l) + \" + \" + show(r) + \")\";\n        case Mul(var l, var r) -&gt; show(l) + \" * \" + show(r);\n        case Neg(var o) -&gt; \"-\" + show(o);\n    };\n}</code></pre>\n<p>There is no <code>default</code> in either method, which is the point: add a <code>Div</code> record and both methods fail to compile until you handle it. The second method shows a nested pattern that matches two numbers directly. When you do not need a component, write an unnamed pattern with <code>_</code> instead of inventing a name, a feature that is final in recent releases and keeps unused names out of the code:</p>\n<pre><code class=\"language-java\">case Add(Num _, Num _) -&gt; \"adding two literals\";</code></pre>\n<p>A <code>switch</code> also handles <code>null</code> on purpose when you ask it to, and a <code>case null</code> replaces a guard clause above the switch:</p>\n<pre><code class=\"language-java\">static String label(PaymentMethod method) {\n    return switch (method) {\n        case null -&gt; \"no payment method\";\n        case Card c -&gt; \"card\";\n        case BankTransfer b -&gt; \"transfer\";\n        case Voucher v -&gt; \"voucher\";\n    };\n}</code></pre>\n<p>Without the <code>case null</code>, a null selector throws <code>NullPointerException</code>, which is the safe default for code that should never see one.</p>\n<h2>A result type instead of an exception for expected failures</h2>\n<p>Sealed interfaces and records make a small result type practical, and it suits the failures that are part of the domain, such as \"the card was declined\", better than an exception does. The caller cannot forget to handle them, because the compiler checks the <code>switch</code>:</p>\n<pre><code class=\"language-java\">public sealed interface Outcome&lt;T&gt; permits Outcome.Success, Outcome.Failure {\n\n    record Success&lt;T&gt;(T value) implements Outcome&lt;T&gt; {}\n    record Failure&lt;T&gt;(String code, String message) implements Outcome&lt;T&gt; {}\n\n    static &lt;T&gt; Outcome&lt;T&gt; success(T value) { return new Success&lt;&gt;(value); }\n    static &lt;T&gt; Outcome&lt;T&gt; failure(String code, String message) { return new Failure&lt;&gt;(code, message); }\n}\n\nOutcome&lt;Receipt&gt; charge(Card card, Money amount) {\n    if (card.expired()) {\n        return Outcome.failure(\"CARD_EXPIRED\", \"The card ended in \" + card.last4() + \" has expired\");\n    }\n    return Outcome.success(gateway.submit(card, amount));\n}\n\nString message = switch (charge(card, amount)) {\n    case Outcome.Success&lt;Receipt&gt;(Receipt r) -&gt; \"Paid, receipt \" + r.reference();\n    case Outcome.Failure&lt;Receipt&gt;(String code, String text) -&gt; \"Declined (\" + code + \"): \" + text;\n};</code></pre>\n<p>Keep exceptions for the unexpected: a network failure, a bug, a corrupted file. A result type for a failure a user can cause, and an exception for a failure only an operator can fix, is a split that reads well and tests well. Do not rebuild a general-purpose monad around it. The two-case sealed interface carries most of the value.</p>\n<h2>Collections and streams, beyond the basics</h2>\n<p>Immutable collection factories are the default now: <code>List.of</code>, <code>Set.of</code>, <code>Map.of</code> and <code>Map.ofEntries</code> reject nulls and cannot be modified, which removes a class of bugs about who may change a list. When you need an unmodifiable copy of something mutable, use <code>List.copyOf</code>. Sequenced collections in Java 21 add the missing operations at the ends:</p>\n<pre><code class=\"language-java\">List&lt;String&gt; steps = new ArrayList&lt;&gt;(List.of(\"validate\", \"price\", \"charge\"));\nsteps.addFirst(\"authenticate\");\nString last = steps.getLast();\nList&lt;String&gt; reversed = steps.reversed();              // a view, not a copy</code></pre>\n<p>A few stream operations are worth knowing because they replace loops with state. <code>Collectors.teeing</code> computes two results in one pass, <code>takeWhile</code> stops at the first failing element and <code>mapMulti</code> replaces a <code>flatMap</code> that would create many tiny streams:</p>\n<pre><code class=\"language-java\">record Stats(long count, double average) {}\n\nStats stats = orders.stream().collect(Collectors.teeing(\n    Collectors.counting(),\n    Collectors.averagingLong(Order::cents),\n    Stats::new));\n\nList&lt;Integer&gt; belowLimit = readings.stream()\n    .takeWhile(r -&gt; r &lt; 1000)\n    .toList();\n\nList&lt;String&gt; tokens = lines.stream()\n    .&lt;String&gt;mapMulti((line, sink) -&gt; {\n        for (String token : line.split(\"\\\\s+\")) {\n            if (!token.isBlank()) sink.accept(token);\n        }\n    })\n    .toList();</code></pre>\n<p>Stream gatherers, final in Java 24, add custom intermediate operations. Windowing is the example people need most, and it used to require an index or a loop:</p>\n<pre><code class=\"language-java\">List&lt;List&lt;Integer&gt;&gt; windows = Stream.of(1, 2, 3, 4, 5, 6, 7)\n    .gather(Gatherers.windowFixed(3))\n    .toList();                                  // [[1, 2, 3], [4, 5, 6], [7]]</code></pre>\n<p>The rule of thumb for streams has not changed. If the pipeline needs mutation of an outer variable, an early return or a checked exception, write the loop. The reader pays for cleverness.</p>\n<h2>Optional, nulls and the small API changes</h2>\n<p><code>Optional</code> is for return types where \"no value\" is a normal answer, and not for fields, parameters or collections. Use its methods and not <code>isPresent()</code> followed by <code>get()</code>:</p>\n<pre><code class=\"language-java\">String city = customers.findById(id)\n    .map(Customer::address)\n    .map(Address::city)\n    .orElse(\"unknown\");\n\ncustomers.findById(id).ifPresentOrElse(\n    c -&gt; log.info(\"found {}\", c.name()),\n    () -&gt; log.warn(\"no customer {}\", id));</code></pre>\n<p>For argument checks, <code>Objects.requireNonNull(value, \"name\")</code> fails with a message, and <code>Objects.requireNonNullElse(value, fallback)</code> replaces a ternary. The file API is shorter than it was: <code>Files.readString</code>, <code>Files.writeString</code> and <code>Path.of</code> replace most reader and stream boilerplate for small files:</p>\n<pre><code class=\"language-java\">String text = Files.readString(Path.of(\"config.json\"));\nFiles.writeString(Path.of(\"out.txt\"), \"done\\n\", StandardOpenOption.CREATE, StandardOpenOption.APPEND);</code></pre>\n<p>For HTTP, <code>java.net.http.HttpClient</code> has been in the JDK since Java 11, supports HTTP/2 and replaces most uses of a third-party client in simple code:</p>\n<pre><code class=\"language-java\">HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();\nHttpRequest request = HttpRequest.newBuilder(URI.create(\"https://api.example.com/ping\"))\n    .timeout(Duration.ofSeconds(3))\n    .header(\"Accept\", \"application/json\")\n    .build();\nHttpResponse&lt;String&gt; response = client.send(request, HttpResponse.BodyHandlers.ofString());</code></pre>\n<h2>Concurrency without the thread pool arithmetic</h2>\n<p>Virtual threads change how you structure concurrent code. The old advice was to size a pool to the work. The new advice is to write blocking code in the straightforward way, start a thread per task and bound what needs bounding with a semaphore or a connection pool:</p>\n<pre><code class=\"language-java\">List&lt;Profile&gt; loadProfiles(List&lt;String&gt; ids) throws Exception {\n    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {\n        List&lt;Future&lt;Profile&gt;&gt; futures = ids.stream()\n            .map(id -&gt; executor.submit(() -&gt; profiles.fetch(id)))\n            .toList();\n\n        List&lt;Profile&gt; result = new ArrayList&lt;&gt;();\n        for (Future&lt;Profile&gt; future : futures) {\n            result.add(future.get());\n        }\n        return result;\n    }\n}</code></pre>\n<p>A thousand profile fetches run concurrently, each on its own virtual thread, and the code reads like a loop. Limit concurrency against a scarce downstream with a <code>Semaphore</code>, not with the size of a pool:</p>\n<pre><code class=\"language-java\">Semaphore limit = new Semaphore(20);\n\nProfile fetchLimited(String id) throws InterruptedException {\n    limit.acquire();\n    try {\n        return profiles.fetch(id);\n    } finally {\n        limit.release();\n    }\n}</code></pre>\n<p>Earlier releases had a caveat: a <code>synchronized</code> block that waited on I/O pinned its carrier thread. Java 24 removed that restriction for monitors, so on a current release the practical limit is native calls and a few specialized cases. Thread-local variables still work with virtual threads, and for per-request data a scoped value is the intended tool, because it is immutable, bounded to a block of code and cheap to inherit by child threads. Structured concurrency, which treats a group of subtasks as one unit that finishes or fails together, is still a preview feature in Java 25, so enable preview in a build only for experiments and plan for the API to change.</p>\n<h2>Upgrading without drama</h2>\n<p>Most upgrades fail on the dependency list and not on the language. A method that works for a codebase moving from Java 8 or 11 to 25 in stages:</p>\n<ol><li>Move to the next long-term support release first, with <code>--release</code> set to the target in the build, so the compiler rejects APIs newer than you intended.</li><li>Run <code>jdeps --jdk-internals --multi-release 25 -R app.jar</code> on the application and its dependencies to find use of JDK internals that newer releases block.</li><li>Upgrade the libraries that the report names. Frameworks such as Spring, Hibernate and Jackson publish the minimum Java version for each release.</li><li>Run the whole test suite on the new JDK before changing any language feature. A green suite on the new runtime is the baseline.</li><li>Adopt features one at a time, in code you are already touching. Convert data classes to records when the class is next edited, not in one commit across the whole repository.</li></ol>\n<pre><code class=\"language-xml\">&lt;properties&gt;\n  &lt;maven.compiler.release&gt;25&lt;/maven.compiler.release&gt;\n&lt;/properties&gt;</code></pre>\n<p>Expect three kinds of breakage: removed or encapsulated APIs, which <code>jdeps</code> finds; changed defaults, such as the character encoding and the default garbage collector, which the release notes list; and libraries compiled with old bytecode tools that do not understand new class file versions. Read the release notes for each long-term support release between your version and the target, since a change that was introduced in an intermediate release is still a change in the one you use.</p>\n<h2>Where to start in an existing codebase</h2>\n<p>Do not begin with a rewrite. Begin with the habits in the table above, applied to code that is changing anyway. A pull request that introduces a record for a new DTO, a <code>switch</code> over a sealed type for a new state machine and a text block for a SQL statement teaches the team the idioms with real examples, and the review conversation does the rest. Keep a short list of the old patterns that new code should avoid, put it in the contribution guide, and let a linter or an IDE inspection enforce the ones that are mechanical. In a year the codebase will read as if it were written for the language you run, and the changes will have cost almost nothing, since each was made beside a change that had to happen anyway.</p>\n<h2>Where this style stops</h2>\n<p>Records are the wrong tool when you need inheritance, lazy-loaded state or framework proxies: JPA entities, most Spring beans and anything a library subclasses at runtime. A sealed hierarchy is wrong for an extension point that other teams implement, since they cannot add a subtype. And if your libraries or your container still run on Java 11, the first step is the upgrade itself, which starts with fixing [<code>UnsupportedClassVersionError</code>](/library/unsupportedclassversionerror-fix-class-file-version-mismatch) when a dependency was built for a newer release than your runtime.</p>\n<p>The errors you will meet on the way are covered one by one: [<code>NullPointerException</code>](/library/nullpointerexception-fix-java-helpful-messages), [<code>ClassCastException</code>](/library/classcastexception-fix-heap-pollution-java) and [<code>ConcurrentModificationException</code>](/library/concurrentmodificationexception-fix-java-collections). For the style rules that go with the features, read <a href=\"/library/clean-code-java-rules-hold-up\">clean code in Java</a>.</p>","date_published":"2026-11-14T04:27:31+00:00","tags":["Java Core"]},{"id":"https://javahacks.dev/library/spring-boot-guide-first-project-production","url":"https://javahacks.dev/library/spring-boot-guide-first-project-production","title":"Spring Boot Guide From First Project to Production","summary":"Build, configure, test and package a Spring Boot 4 service, then see what separates a demo from a service you can run in production.","content_html":"<p>A Spring Boot application that runs on your laptop and one that survives a deploy are separated by a short list of settings, and nobody tells you the list until the first outage. This guide follows one small service from the Initializr page to a container image, on Spring Boot 4 and JDK 25, and stops at each setting that matters in production. If a step fails for you, the matching fix post is linked at the point where it usually does.</p>\n<p>Spring Boot sits on the Spring container, so when a bean misbehaves, <a href=\"/library/spring-container-works-really\">how the Spring container works</a> is the page to read next.</p>\n<h2>Start from the Initializr</h2>\n<p>Create the project at start.spring.io with Maven, Java 25 and four dependencies: Spring Web, Validation, Actuator and Spring Data JPA with PostgreSQL. Resist adding more. Each starter brings auto-configuration, and the more of it you carry, the longer the list of reasons the application can fail to start.</p>\n<p>The generated main class is the whole entry point:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/ShopApplication.java\"><code class=\"language-java\">@SpringBootApplication\npublic class ShopApplication {\n\n    public static void main(String[] args) {\n        SpringApplication.run(ShopApplication.class, args);\n    }\n}</code></pre>\n<p><code>@SpringBootApplication</code> combines <code>@Configuration</code>, <code>@EnableAutoConfiguration</code> and <code>@ComponentScan</code>. The scan starts in the package of this class, which is why a controller placed in a sibling package is silently ignored and returns a <a href=\"/library/whitelabel-error-page-spring-boot-fix\">whitelabel 404 page</a>.</p>\n<h2>Keep configuration out of the code</h2>\n<p>Spring Boot reads <code>application.properties</code> or <code>application.yaml</code> from the classpath (<a href=\"https://docs.spring.io/spring-boot/reference/features/external-config.html\">externalized configuration</a>), then overlays profile files, environment variables and command-line arguments, with the later sources winning. The environment variable <code>SPRING_DATASOURCE_URL</code> overrides <code>spring.datasource.url</code> because relaxed binding maps one to the other.</p>\n<pre data-filename=\"src/main/resources/application.yaml\"><code class=\"language-yaml\">spring:\n  datasource:\n    url: jdbc:postgresql://localhost:5432/shop\n    username: shop\n  jpa:\n    open-in-view: false\nserver:\n  shutdown: graceful</code></pre>\n<p>The password is not in the file. In every environment but a laptop it arrives as <code>SPRING_DATASOURCE_PASSWORD</code>. The first time you forget to supply the datasource at all, you get the <a href=\"/library/failed-configure-datasource-fix-spring-boot\">Failed to configure a DataSource</a> report.</p>\n<p><code>spring.jpa.open-in-view=false</code> is a deliberate choice. The default keeps a database connection open for the entire web request, which hides lazy-loading mistakes in development and drains the pool under slow clients. Turning it off surfaces those mistakes early, and [<code>LazyInitializationException</code>](/library/lazyinitializationexception-fix-spring-boot-hibernate) is how they show up.</p>\n<h2>Validate properties at startup</h2>\n<p>Bind your own settings to a typed object so a typo cannot reach production:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/ShopProperties.java\"><code class=\"language-java\">@ConfigurationProperties(prefix = \"shop\")\n@Validated\npublic record ShopProperties(\n        @NotBlank String currency,\n        @Min(1) @Max(100) int pageSize) {\n}</code></pre>\n<p>Enable it with <code>@ConfigurationPropertiesScan</code> on the application class. If <code>shop.page-size</code> is missing or <code>0</code>, the application refuses to start and names the property. That is the behavior you want: a failure on deploy, with the property in the message, instead of a surprise on the first request. A missing <code>@Value</code> placeholder fails the same way, and <a href=\"/library/could-not-resolve-placeholder-fix-spring\">the placeholder error</a> explains its message.</p>\n<h2>Write a controller and test it as a slice</h2>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/ProductController.java\"><code class=\"language-java\">@RestController\n@RequestMapping(\"/api/products\")\nclass ProductController {\n\n    private final ProductRepository products;\n\n    ProductController(ProductRepository products) {\n        this.products = products;\n    }\n\n    @GetMapping(\"/{id}\")\n    ResponseEntity&lt;Product&gt; byId(@PathVariable long id) {\n        return products.findById(id)\n                .map(ResponseEntity::ok)\n                .orElse(ResponseEntity.notFound().build());\n    }\n}</code></pre>\n<p>Constructor injection needs no annotation when the class has one constructor. Test the web layer without starting the database by loading only the MVC slice:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/shop/ProductControllerTest.java\"><code class=\"language-java\">@WebMvcTest(ProductController.class)\nclass ProductControllerTest {\n\n    @Autowired MockMvc mvc;\n    @MockitoBean ProductRepository products;\n\n    @Test\n    void returns404ForUnknownProduct() throws Exception {\n        given(products.findById(7L)).willReturn(Optional.empty());\n\n        mvc.perform(get(\"/api/products/7\"))\n           .andExpect(status().isNotFound());\n    }\n}</code></pre>\n<p><code>@MockitoBean</code> is the Spring Framework 6.2 replacement for the deprecated <code>@MockBean</code>. A full-context <code>@SpringBootTest</code> belongs to a handful of end-to-end checks; the slices keep the suite fast. If the context fails to load, <a href=\"/library/failed-load-applicationcontext-fix-spring-boot\">Failed to load ApplicationContext</a> lists the causes in order.</p>\n<h2>Add Actuator, and be careful what it exposes</h2>\n<p>Actuator turns on health, metrics and info endpoints (<a href=\"https://docs.spring.io/spring-boot/reference/actuator/index.html\">Actuator reference</a>). Over HTTP, Spring Boot exposes only <code>health</code> by default, and you should keep it that way until you know who can reach the port.</p>\n<pre><code class=\"language-yaml\">management:\n  endpoints:\n    web:\n      exposure:\n        include: health, info\n  endpoint:\n    health:\n      probes:\n        enabled: true</code></pre>\n<p>With probes enabled, <code>/actuator/health/liveness</code> and <code>/actuator/health/readiness</code> exist for Kubernetes. Liveness answers whether the process should be restarted, so it must not depend on the database; readiness answers whether it should receive traffic, so it can. Mixing the two is how a database blip turns into a restart loop. Never expose <code>env</code>, <code>heapdump</code> or <code>shutdown</code> on a public port.</p>\n<h2>Shut down without dropping requests</h2>\n<p>With <code>server.shutdown=graceful</code>, Spring Boot stops accepting new connections on SIGTERM and waits for active requests, up to <code>spring.lifecycle.timeout-per-shutdown-phase</code> (30 seconds by default). Your orchestrator's termination grace period must be longer than that value, or the process is killed first.</p>\n<h2>Package a layered image</h2>\n<p>The Maven plugin builds an OCI image without a Dockerfile:</p>\n<pre><code class=\"language-bash\">./mvnw -q spring-boot:build-image -Dspring-boot.build-image.imageName=shop:1.0</code></pre>\n<p>The image uses Cloud Native Buildpacks, which calculate memory settings from the container limit at startup. If you write your own Dockerfile instead, use the layered jar so dependencies and your code land in separate layers, and read <a href=\"/library/spring-boot-docker-image-not-starting\">the Docker image that will not start</a> when the container exits immediately.</p>\n<h2>Read the failure analysis before anything else</h2>\n<p>Spring Boot prints a structured report when startup fails: a description, then an action. The two lines tell you most of what the stack trace will. The port conflict is the classic case, and <a href=\"/library/port-8080-already-use-spring-boot\">port 8080 already in use</a> shows how to find the process. For anything else, <a href=\"/library/spring-boot-application-failed-start-fix\">application failed to start</a> is the checklist.</p>\n<h2>Persistence: an entity, a repository and a migration</h2>\n<p>The generated project has a datasource and no tables. Add the three pieces that make persistence reproducible. First, the entity. It is an ordinary class with a protected constructor for JPA, because a record cannot be proxied or mutated by Hibernate:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/Product.java\"><code class=\"language-java\">@Entity\n@Table(name = \"products\")\npublic class Product {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private Long id;\n\n    @Column(nullable = false, length = 120)\n    private String name;\n\n    @Column(nullable = false, precision = 19, scale = 2)\n    private BigDecimal price;\n\n    @Version\n    private long version;\n\n    protected Product() {}\n\n    public Product(String name, BigDecimal price) {\n        this.name = name;\n        this.price = price;\n    }\n\n    public Long getId() { return id; }\n    public String getName() { return name; }\n    public BigDecimal getPrice() { return price; }\n}</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/ProductRepository.java\"><code class=\"language-java\">public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {\n\n    List&lt;Product&gt; findByNameContainingIgnoreCaseOrderByName(String fragment);\n}</code></pre>\n<p>Second, the schema belongs in a migration, not in a Hibernate setting. Add the Flyway dependency (<code>org.flywaydb:flyway-core</code> and the PostgreSQL module for your Flyway version) and write the first version of the table:</p>\n<pre data-filename=\"src/main/resources/db/migration/V1__create_products.sql\"><code class=\"language-sql\">create table products (\n    id         bigint generated always as identity primary key,\n    name       varchar(120)   not null,\n    price      numeric(19, 2) not null check (price &gt;= 0),\n    version    bigint         not null default 0\n);\n\ncreate index products_name_idx on products (lower(name));</code></pre>\n<p>Third, tell Hibernate to verify and not to create:</p>\n<pre><code class=\"language-yaml\">spring:\n  jpa:\n    hibernate:\n      ddl-auto: validate\n  flyway:\n    enabled: true</code></pre>\n<p>Now an application that starts has a schema that matches its mapping, and one that does not match refuses to start with a message that names the column. A migration that has already run in any shared environment is never edited, since Flyway stores a checksum and fails the next start if the file changed. A fix is a new version, <code>V2__...</code>. The mapping choices behind entities, such as lazy associations and fetch plans, are in <a href=\"/library/hibernate-jpa-guide-without-surprises\">the Hibernate guide</a>.</p>\n<h2>Request objects, validation and one error format</h2>\n<p>Controllers should accept their own types, and never the entity. A record per request keeps the contract explicit and carries the validation rules:</p>\n<pre><code class=\"language-java\">public record CreateProduct(\n        @NotBlank @Size(max = 120) String name,\n        @NotNull @DecimalMin(\"0.00\") @Digits(integer = 17, fraction = 2) BigDecimal price) {\n}\n\npublic record ProductView(long id, String name, BigDecimal price) {\n    static ProductView of(Product p) {\n        return new ProductView(p.getId(), p.getName(), p.getPrice());\n    }\n}</code></pre>\n<pre><code class=\"language-java\">@PostMapping\nResponseEntity&lt;ProductView&gt; create(@Valid @RequestBody CreateProduct request, UriComponentsBuilder uri) {\n    Product saved = products.save(new Product(request.name(), request.price()));\n    URI location = uri.path(\"/api/products/{id}\").buildAndExpand(saved.getId()).toUri();\n    return ResponseEntity.created(location).body(ProductView.of(saved));\n}</code></pre>\n<p>A request that breaks a rule must come back as something a client can parse. Turn on the problem-details support and add one advice class for the errors that are yours:</p>\n<pre><code class=\"language-yaml\">spring:\n  mvc:\n    problemdetails:\n      enabled: true</code></pre>\n<pre><code class=\"language-java\">@RestControllerAdvice\nclass ApiExceptionHandler {\n\n    @ExceptionHandler(ProductNotFound.class)\n    ProblemDetail notFound(ProductNotFound e) {\n        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());\n        problem.setTitle(\"Product not found\");\n        return problem;\n    }\n\n    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)\n    ProblemDetail conflict() {\n        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,\n            \"The product was changed by someone else. Reload and try again.\");\n    }\n}</code></pre>\n<p>With that in place, a bad body yields <code>400</code> with <code>application/problem+json</code> that names the failing field, a missing product yields <code>404</code> in the same format, and a lost update yields <code>409</code>. Every client then writes one error handler. The design rules behind these choices are the usual REST ones.</p>\n<h2>One configuration, three environments</h2>\n<p>Spring Boot loads <code>application.yaml</code> first and then any profile file that matches an active profile, so environment differences go in small overlay files. A layout that works for most teams:</p>\n<pre data-filename=\"src/main/resources/application-local.yaml\"><code class=\"language-yaml\">spring:\n  datasource:\n    url: jdbc:postgresql://localhost:5432/shop\n    username: shop\n    password: shop\nlogging:\n  level:\n    org.hibernate.SQL: DEBUG</code></pre>\n<pre data-filename=\"src/main/resources/application-prod.yaml\"><code class=\"language-yaml\">spring:\n  datasource:\n    url: ${DB_URL}\n    username: ${DB_USER}\n    password: ${DB_PASSWORD}\n  jpa:\n    show-sql: false\nmanagement:\n  endpoints:\n    web:\n      exposure:\n        include: health, info, prometheus</code></pre>\n<p>Activate a profile with <code>SPRING_PROFILES_ACTIVE=prod</code> in the environment. Do not commit real credentials in the <code>local</code> file beyond a throwaway development password, and never put a production value in a file in the repository. On Kubernetes, mounted secrets can be read as configuration without environment variables at all:</p>\n<pre><code class=\"language-yaml\">spring:\n  config:\n    import: \"optional:configtree:/etc/secrets/\"</code></pre>\n<p>A file <code>/etc/secrets/spring.datasource.password</code> then becomes the property of the same name, which keeps the password out of <code>docker inspect</code> and process listings. Print the effective configuration of a running instance, with secrets masked, through the <code>configprops</code> and <code>env</code> Actuator endpoints in a protected profile, and not by guessing from the files.</p>\n<h2>Logs you can search</h2>\n<p>Plain text lines are fine on a laptop and painful in a log platform. Spring Boot can write structured JSON through a property, with no extra dependency:</p>\n<pre><code class=\"language-yaml\">logging:\n  structured:\n    format:\n      console: ecs</code></pre>\n<p>Each line becomes a JSON object with a timestamp, level, logger, message and any MDC fields, so a platform can filter by field instead of parsing text. Put a request id in the MDC in a filter, as in <a href=\"/library/debug-production-java-logs-issue-only\">debugging production with logs</a>, and every line of a request carries it. Choose levels on purpose: <code>INFO</code> for events a person operating the service wants to read, <code>WARN</code> for something recoverable that needs attention, <code>ERROR</code> only when someone should be paged, and <code>DEBUG</code> for development. Never log passwords, tokens, full card numbers or whole request bodies.</p>\n<h2>Metrics and a health check that tells the truth</h2>\n<p>Actuator publishes JVM, HTTP and connection pool metrics through Micrometer with no code. Add the metrics that describe your own business, because the platform cannot guess them:</p>\n<pre><code class=\"language-java\">@Service\nclass CheckoutService {\n\n    private final Counter checkouts;\n    private final Timer paymentTimer;\n\n    CheckoutService(MeterRegistry registry) {\n        this.checkouts = Counter.builder(\"shop.checkouts\").tag(\"result\", \"completed\").register(registry);\n        this.paymentTimer = Timer.builder(\"shop.payment.duration\").publishPercentileHistogram().register(registry);\n    }\n\n    void checkout(Cart cart) {\n        paymentTimer.record(() -&gt; payments.charge(cart));\n        checkouts.increment();\n    }\n}</code></pre>\n<p>Add <code>micrometer-registry-prometheus</code> and expose <code>prometheus</code> in the management endpoints, and a scraper reads <code>/actuator/prometheus</code>. A custom health indicator reports a dependency that the default checks do not know about:</p>\n<pre><code class=\"language-java\">@Component\nclass PaymentGatewayHealth implements HealthIndicator {\n\n    private final PaymentClient client;\n\n    PaymentGatewayHealth(PaymentClient client) {\n        this.client = client;\n    }\n\n    @Override\n    public Health health() {\n        try {\n            client.ping();\n            return Health.up().build();\n        } catch (RuntimeException e) {\n            return Health.down().withDetail(\"error\", e.getClass().getSimpleName()).build();\n        }\n    }\n}</code></pre>\n<p>Keep a dependency like this in the readiness group and out of liveness, as described earlier: if the gateway is down, the instance should stop receiving traffic that needs it, and a restart would not help.</p>\n<pre><code class=\"language-yaml\">management:\n  endpoint:\n    health:\n      group:\n        readiness:\n          include: readinessState,db,paymentGateway</code></pre>\n<h2>Secure the API from the first commit</h2>\n<p>A service without authentication is a demo. For an API that accepts bearer tokens from an identity provider, the configuration is short, and the default must be to deny:</p>\n<pre><code class=\"language-java\">@Configuration\n@EnableMethodSecurity\nclass SecurityConfig {\n\n    @Bean\n    SecurityFilterChain api(HttpSecurity http) throws Exception {\n        return http\n            .csrf(csrf -&gt; csrf.disable())\n            .sessionManagement(s -&gt; s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))\n            .authorizeHttpRequests(auth -&gt; auth\n                .requestMatchers(\"/actuator/health/**\").permitAll()\n                .requestMatchers(HttpMethod.GET, \"/api/products/**\").hasAuthority(\"SCOPE_catalog:read\")\n                .requestMatchers(\"/api/**\").hasAuthority(\"SCOPE_catalog:write\")\n                .anyRequest().denyAll())\n            .oauth2ResourceServer(oauth -&gt; oauth.jwt(Customizer.withDefaults()))\n            .build();\n    }\n}</code></pre>\n<pre><code class=\"language-yaml\">spring:\n  security:\n    oauth2:\n      resourceserver:\n        jwt:\n          issuer-uri: https://auth.example.com/realms/shop</code></pre>\n<p>CSRF protection is off here because the API holds no session cookie and authenticates with a header the browser does not attach on its own, which is the condition for turning it off safely. The final <code>denyAll()</code> means that a new endpoint nobody listed is closed until somebody decides who may call it. The explanations of each line are in <a href=\"/library/spring-security-lambda-dsl-configuration-explained\">the Spring Security lambda DSL post</a>.</p>\n<h2>Outbound calls, pools and threads</h2>\n<p>Three settings decide how the service behaves when something it depends on is slow. Give every outbound HTTP call a timeout, because the default is often infinite:</p>\n<pre><code class=\"language-java\">@Bean\nRestClient paymentsClient(RestClient.Builder builder) {\n    var factory = new JdkClientHttpRequestFactory(\n        HttpClient.newBuilder().connectTimeout(Duration.ofMillis(500)).build());\n    factory.setReadTimeout(Duration.ofSeconds(2));\n    return builder.baseUrl(\"https://payments.example.com\").requestFactory(factory).build();\n}</code></pre>\n<p>Size the database pool for the work and not for the thread count, with a short wait before a request gives up:</p>\n<pre><code class=\"language-yaml\">spring:\n  datasource:\n    hikari:\n      maximum-pool-size: 10\n      connection-timeout: 2000</code></pre>\n<p>Then decide on virtual threads. On a current JDK, one property gives each request a virtual thread, which suits services that spend their time waiting on I/O:</p>\n<pre><code class=\"language-yaml\">spring:\n  threads:\n    virtual:\n      enabled: true</code></pre>\n<p>The pool becomes the throttle that protects the database, so keep the pool size where it was, and do not raise it to match the number of concurrent requests. The sizing arithmetic is in <a href=\"/library/hikaricp-pool-size-sizing-formula-common\">the HikariCP pool size post</a>.</p>\n<h2>The integration test that proves the whole thing starts</h2>\n<p>Slice tests keep the suite fast, and one full test with a real database proves that the migrations, the mapping, the security and the controllers work together:</p>\n<pre><code class=\"language-java\">@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\n@Testcontainers\nclass ShopApplicationIT {\n\n    @Container\n    @ServiceConnection\n    static PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;(\"postgres:17\");\n\n    @Autowired TestRestTemplate rest;\n\n    @Test\n    void healthIsUpAndAProductCanBeCreatedAndRead() {\n        assertThat(rest.getForEntity(\"/actuator/health\", String.class).getStatusCode())\n            .isEqualTo(HttpStatus.OK);\n\n        ResponseEntity&lt;ProductView&gt; created = rest.withBasicAuth(\"test\", \"test\")\n            .postForEntity(\"/api/products\", new CreateProduct(\"Mug\", new BigDecimal(\"12.50\")), ProductView.class);\n\n        assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED);\n        assertThat(created.getHeaders().getLocation()).isNotNull();\n    }\n}</code></pre>\n<p>Test security with a test profile that supplies a fixed test token or a mock JWT decoder, and not with credentials copied from production. When the test fails at startup, read the report from the first section of this guide: a Flyway checksum mismatch, a validation error on a property and a missing bean all name themselves in the first lines.</p>\n<h2>A Dockerfile that uses the layers</h2>\n<p>The buildpack image is convenient. When you need a Dockerfile, use the layered jar so that the dependencies sit in their own layer and an ordinary code change rebuilds only a few kilobytes:</p>\n<pre><code class=\"language-dockerfile\">FROM eclipse-temurin:25-jdk AS build\nWORKDIR /workspace\nCOPY .mvn/ .mvn/\nCOPY mvnw pom.xml ./\nRUN ./mvnw -q dependency:go-offline\nCOPY src/ src/\nRUN ./mvnw -q -DskipTests package \\\n &amp;&amp; java -Djarmode=tools -jar target/shop.jar extract --layers --destination extracted\n\nFROM eclipse-temurin:25-jre\nWORKDIR /app\nRUN useradd --system --uid 10001 app\nCOPY --from=build /workspace/extracted/dependencies/ ./\nCOPY --from=build /workspace/extracted/spring-boot-loader/ ./\nCOPY --from=build /workspace/extracted/snapshot-dependencies/ ./\nCOPY --from=build /workspace/extracted/application/ ./\nUSER app\nEXPOSE 8080\nENTRYPOINT [\"java\", \"-XX:MaxRAMPercentage=65\", \"-jar\", \"shop.jar\"]</code></pre>\n<p>Each line of this file has a reason, explained in <a href=\"/library/java-dockerfile-write-right-way\">writing a Dockerfile for Java the right way</a>. Check the Spring Boot container images chapter for the exact <code>extract</code> command your version supports.</p>\n<h2>The deployment that matches the settings</h2>\n<p>The application settings only work if the platform cooperates. A Kubernetes deployment that agrees with everything above:</p>\n<pre><code class=\"language-yaml\">apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: shop\nspec:\n  replicas: 3\n  selector:\n    matchLabels: { app: shop }\n  template:\n    metadata:\n      labels: { app: shop }\n    spec:\n      terminationGracePeriodSeconds: 45\n      containers:\n        - name: shop\n          image: registry.example.com/shop:1.0\n          ports:\n            - containerPort: 8080\n          envFrom:\n            - secretRef: { name: shop-db }\n          env:\n            - name: SPRING_PROFILES_ACTIVE\n              value: prod\n          resources:\n            requests: { cpu: \"500m\", memory: \"768Mi\" }\n            limits: { memory: \"768Mi\" }\n          startupProbe:\n            httpGet: { path: /actuator/health/liveness, port: 8080 }\n            failureThreshold: 30\n            periodSeconds: 2\n          livenessProbe:\n            httpGet: { path: /actuator/health/liveness, port: 8080 }\n          readinessProbe:\n            httpGet: { path: /actuator/health/readiness, port: 8080 }</code></pre>\n<p>The grace period of 45 seconds exceeds the 30-second shutdown phase, so Kubernetes does not kill a pod that is still draining. The memory limit is set equal to the request, and the JVM sizes its heap as a share of it. The startup probe gives a slow start up to a minute before liveness begins to judge it, so a cold JVM is not killed in a restart loop. If a pod is still killed, see the post on Java container OOMKilled errors.</p>\n<h2>A checklist before the first production deploy</h2>\n<table><thead><tr><th>Question</th><th>Where it is answered</th></tr></thead><tbody><tr><td>Does the application start with only environment variables and a profile?</td><td><code>application-prod.yaml</code> and a staging run</td></tr><tr><td>Are all secrets outside the repository and the image?</td><td>Secret store, <code>configtree</code></td></tr><tr><td>Does a missing required property stop the startup with a clear message?</td><td><code>@ConfigurationProperties</code> with <code>@Validated</code></td></tr><tr><td>Is the schema owned by migrations and verified at startup?</td><td>Flyway and <code>ddl-auto: validate</code></td></tr><tr><td>Is every outbound call bounded by a timeout?</td><td>Client factories</td></tr><tr><td>Are liveness and readiness separate, and does liveness avoid dependencies?</td><td>Health groups</td></tr><tr><td>Do SIGTERM and the grace period let in-flight requests finish?</td><td><code>server.shutdown</code>, pod settings</td></tr><tr><td>Can you find one request in the logs by an id?</td><td>Structured logging and a filter</td></tr><tr><td>Do you know the three numbers that mean healthy, such as error rate, p99 latency and pool wait?</td><td>Dashboards from Micrometer</td></tr><tr><td>Can you roll back, and have you tried it?</td><td>The deployment pipeline</td></tr></tbody></table>\n<p>If the answer to any row is unknown, the work for the week is clear. Most outages in a first production service are on this list, and the list is short enough to finish before the launch.</p>\n<h2>Reading the startup failures you will meet</h2>\n<p>A startup that fails prints a report with a description and an action. Learn the common ones by sight:</p>\n<table><thead><tr><th>First line of the description</th><th>Usual cause</th><th>First move</th></tr></thead><tbody><tr><td><code>Failed to configure a DataSource: 'url' attribute is not specified</code></td><td>No datasource properties in this profile</td><td>Set the URL, or check which profile is active</td></tr><tr><td><code>Web server failed to start. Port 8080 was already in use</code></td><td>Another process holds the port</td><td>Find it with <code>lsof -i :8080</code> or change the port</td></tr><tr><td><code>Parameter 0 of constructor in ... required a bean of type ... that could not be found</code></td><td>Missing bean, or a package outside the scan</td><td>Check the package of the main class</td></tr><tr><td><code>Validation failed for ... shop.page-size</code></td><td>A required property is missing or out of range</td><td>Set it for this environment</td></tr><tr><td><code>Migration checksum mismatch for migration version 1</code></td><td>A shipped migration was edited</td><td>Restore the file, add a new version</td></tr><tr><td><code>Schema-validation: missing column [...] in table [...]</code></td><td>The mapping and the migrations disagree</td><td>Add the migration, or fix the field</td></tr></tbody></table>\n<p>Read the description before the stack trace, because it is written to be read by the person deploying, and the trace is written for the person fixing the framework. When the description is not enough, start the application with <code>--debug</code> and read the condition evaluation report, as described in the Spring Boot debugging post.</p>\n<h2>What to do in the second week</h2>\n<p>A service that passes the checklist is ready for its first users, and it is not finished. The second week is for the things that only real traffic teaches. Watch the dashboards you built and write down the three numbers that mean healthy: the error rate, the high percentile of latency, and how long requests wait for a database connection. Set an alert on each, with a threshold you can defend, and a link to the runbook in the alert text. Run the rollback once, on purpose, during working hours, so that the first rollback is not also the first time anyone has tried it.</p>\n<p>Then read the logs from the first days with fresh eyes. Warnings that repeat are either noise to remove or a problem to fix, and an application whose logs are quiet when healthy is one where a new line stands out. Finally, schedule the dull maintenance now: a dependency update every month, a review of the pool and timeout settings after the first traffic peak and a restore test of the database backup. None of it is glamorous, and it is what separates a service that was launched from one that is operated.</p>\n<h2>When this setup is the wrong fit</h2>\n<p>This guide assumes a conventional servlet application on a JVM. If startup time and memory dominate the bill, as in scale-to-zero functions, look at <a href=\"/library/quarkus-spring-developers\">Quarkus for Spring developers</a> before you add native-image complexity to Spring. If the service is a thin transformation with no database, the Actuator and layered image advice still holds, but the persistence settings do not.</p>","date_published":"2026-11-14T04:26:31+00:00","tags":["Spring Boot"]},{"id":"https://javahacks.dev/library/spring-container-works-really","url":"https://javahacks.dev/library/spring-container-works-really","title":"How Spring Container Works and Why Proxies Surprise You","summary":"Follow a bean from definition to proxy to destruction, and learn why scopes, proxies and transactions behave the way they do inside the container.","content_html":"<p>A Spring application is a container, a set of definitions and a lot of wrapping. Understanding those three things explains why <code>@Transactional</code> fails when you call a method on <code>this</code>, why a singleton holds a stale request-scoped bean forever, and why a circular dependency is an error in one setup and silently works in another. This guide opens the container up on Spring Framework 7 and traces one bean through its life, with the failure modes at each stage.</p>\n<p>If you are new to the idea of letting a framework hand you your collaborators, start with <a href=\"/library/dependency-injection-really-spring-uses\">what dependency injection really is</a>, then come back.</p>\n<h2>The container reads definitions, not classes</h2>\n<p>An <code>ApplicationContext</code> holds a registry of bean definitions (<a href=\"https://docs.spring.io/spring-framework/reference/core/beans.html\">core container reference</a>): a class name, a scope, constructor arguments, init and destroy methods and a list of dependencies. A definition comes from component scanning, a <code>@Bean</code> method, an <code>@Import</code> or auto-configuration. The container does not care which.</p>\n<p>You can see the registry yourself:</p>\n<pre><code class=\"language-java\">try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {\n    for (String name : context.getBeanDefinitionNames()) {\n        System.out.println(name + \" -&gt; \" + context.getBeanDefinition(name).getScope());\n    }\n}</code></pre>\n<p>The same class can appear twice under two names with two sets of arguments. That is why an injection point that matches two definitions throws [<code>NoUniqueBeanDefinitionException</code>](/library/nouniquebeandefinitionexception-fix-qualifier), and one that matches none throws [<code>NoSuchBeanDefinitionException</code>](/library/nosuchbeandefinitionexception-fix-spring).</p>\n<h2>The life of one singleton</h2>\n<p>For each singleton, in dependency order, the container runs the same sequence:</p>\n<ol><li>Instantiate the object through its constructor, resolving constructor arguments first.</li><li>Populate fields and setters marked for injection.</li><li>Call <code>Aware</code> callbacks such as <code>BeanNameAware</code>.</li><li>Run each <code>BeanPostProcessor.postProcessBeforeInitialization</code>.</li><li>Call <code>@PostConstruct</code>, then <code>afterPropertiesSet</code>, then the <code>initMethod</code>.</li><li>Run each <code>BeanPostProcessor.postProcessAfterInitialization</code>, which is where proxies are created.</li><li>Store the result in the singleton cache.</li></ol>\n<p>At shutdown, <code>@PreDestroy</code> and <code>destroyMethod</code> run in reverse dependency order. Because singletons are created eagerly by default, a broken definition fails the startup, and [<code>BeanCreationException</code>](/library/beancreationexception-error-creating-bean-fix-name) is the wrapper you read first. The real cause is at the bottom of its <code>Caused by</code> chain.</p>\n<h2>Proxies are the product of step six</h2>\n<p><code>@Transactional</code>, <code>@Async</code>, <code>@Cacheable</code> and method security work by wrapping your bean in a proxy (<a href=\"https://docs.spring.io/spring-framework/reference/core/aop/proxying.html\">proxying mechanisms</a>). Spring creates a JDK dynamic proxy when the bean implements an interface and the configuration asks for it, and a CGLIB subclass otherwise. Spring Boot defaults to CGLIB (<code>spring.aop.proxy-target-class=true</code>).</p>\n<pre><code class=\"language-java\">@Service\nclass InvoiceService {\n\n    @Transactional\n    public void create(Invoice invoice) {\n        save(invoice);\n    }\n\n    @Transactional(propagation = Propagation.REQUIRES_NEW)\n    public void save(Invoice invoice) {\n        // intended to run in its own transaction\n    }\n}</code></pre>\n<p>When a controller calls <code>invoiceService.create(...)</code>, it holds the proxy, so the transaction begins. Inside <code>create</code>, the call to <code>save</code> is a plain Java call on <code>this</code>. It never touches the proxy, so <code>REQUIRES_NEW</code> is ignored. The full diagnosis is in [<code>@Transactional</code> not working on self-called methods](/library/transactional-not-working-fix-self-called). The fix is to move <code>save</code> to another bean, which also makes the transaction boundary visible in the code.</p>\n<p>CGLIB proxies also impose rules: the class cannot be <code>final</code>, and proxied methods cannot be <code>final</code> or <code>private</code>, because the proxy overrides them. A <code>final</code> method on a proxied bean runs against the proxy's uninitialized fields and throws a confusing <code>NullPointerException</code>.</p>\n<h2>Scopes and the singleton trap</h2>\n<p>The default scope is singleton: one instance per container. <code>prototype</code> creates a new instance per lookup, and the web scopes (<code>request</code>, <code>session</code>) create one per HTTP request or session.</p>\n<p>The trap is injecting a short-lived bean into a long-lived one. A singleton is wired once, so it receives the first request-scoped instance and keeps it. Two safe patterns exist:</p>\n<pre><code class=\"language-java\">@Component\n@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)\nclass RequestContext { /* per-request state */ }\n\n@Service\nclass Reporter {\n    private final ObjectProvider&lt;ReportSession&gt; sessions;\n\n    Reporter(ObjectProvider&lt;ReportSession&gt; sessions) {\n        this.sessions = sessions;\n    }\n\n    void run() {\n        ReportSession session = sessions.getObject(); // fresh prototype each call\n    }\n}</code></pre>\n<p>The scoped proxy defers the lookup to each call. The <code>ObjectProvider</code> makes the lookup explicit. Use the proxy when the code should not know about scope and the provider when it should.</p>\n<h2>Dependency cycles</h2>\n<p>With constructor injection, A needing B and B needing A cannot be satisfied, because neither can be built first. Spring reports it at startup as [<code>BeanCurrentlyInCreationException</code>](/library/beancurrentlyincreationexception-fix-spring). Since Spring Boot 2.6, circular references are prohibited by default even for setter injection, which used to hide the design problem. Allowing them again with <code>spring.main.allow-circular-references=true</code> is a patch, not a fix. The real fix is to extract the shared behavior into a third bean. <a href=\"/library/circular-dependency-spring-boot-fix-errors\">Circular dependencies in Spring Boot</a> covers the options.</p>\n<h2>Why constructor injection wins</h2>\n<p>Field injection hides dependencies, prevents <code>final</code> fields and makes the class impossible to construct in a plain unit test without reflection. Constructor injection makes the dependency list the first thing a reader sees and lets the compiler help. If an injection fails, [<code>UnsatisfiedDependencyException</code>](/library/unsatisfieddependencyexception-fix-spring) names the parameter that broke.</p>\n<h2>What to read when the container surprises you</h2>\n<table><thead><tr><th>Symptom</th><th>First thing to check</th></tr></thead><tbody><tr><td>Annotation has no effect</td><td>Is the call going through the proxy?</td></tr><tr><td>Two beans match</td><td>Add <code>@Qualifier</code> or <code>@Primary</code>, or rename the parameter</td></tr><tr><td>Startup fails on a bean you never wrote</td><td>Read the bottom <code>Caused by</code></td></tr><tr><td>Value never changes between requests</td><td>A request-scoped bean injected into a singleton</td></tr><tr><td><code>@Transactional</code> ignored</td><td>Self-invocation, <code>private</code> method, or <code>final</code> class</td></tr></tbody></table>\n<h2>Build a toy container to see what it does</h2>\n<p>The quickest way to demystify a container is to write a small one. This is about seventy lines of plain Java, with no Spring in it, that does what the first half of this guide describes: it holds definitions, creates singletons in dependency order through constructors, caches them and lets a post-processor wrap the result:</p>\n<pre><code class=\"language-java\">import java.lang.reflect.*;\nimport java.util.*;\nimport java.util.function.UnaryOperator;\n\npublic class MiniContainer {\n\n    private final Map&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt; definitions = new LinkedHashMap&lt;&gt;();\n    private final Map&lt;Class&lt;?&gt;, Object&gt; singletons = new HashMap&lt;&gt;();\n    private final Set&lt;Class&lt;?&gt;&gt; inCreation = new HashSet&lt;&gt;();\n    private final List&lt;UnaryOperator&lt;Object&gt;&gt; postProcessors = new ArrayList&lt;&gt;();\n\n    public &lt;T&gt; void register(Class&lt;T&gt; type, Class&lt;? extends T&gt; implementation) {\n        definitions.put(type, implementation);\n    }\n\n    public void addPostProcessor(UnaryOperator&lt;Object&gt; processor) {\n        postProcessors.add(processor);\n    }\n\n    public void refresh() {\n        definitions.keySet().forEach(this::get);          // eager singletons, like Spring\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public &lt;T&gt; T get(Class&lt;T&gt; type) {\n        Object existing = singletons.get(type);\n        if (existing != null) return (T) existing;\n\n        if (!inCreation.add(type)) {\n            throw new IllegalStateException(\"Circular dependency while creating \" + type.getSimpleName());\n        }\n        try {\n            Class&lt;?&gt; implementation = definitions.get(type);\n            if (implementation == null) {\n                throw new IllegalStateException(\"No bean of type \" + type.getName());\n            }\n            Constructor&lt;?&gt; constructor = implementation.getDeclaredConstructors()[0];\n            Object[] args = Arrays.stream(constructor.getParameterTypes()).map(this::get).toArray();\n            Object bean = constructor.newInstance(args);          // steps 1 and 2: instantiate and inject\n            for (UnaryOperator&lt;Object&gt; processor : postProcessors) {\n                bean = processor.apply(bean);                      // step 6: possibly wrap in a proxy\n            }\n            singletons.put(type, bean);\n            return (T) bean;\n        } catch (ReflectiveOperationException e) {\n            throw new IllegalStateException(\"Cannot create \" + type.getName(), e);\n        } finally {\n            inCreation.remove(type);\n        }\n    }\n}</code></pre>\n<p>Use it with two beans and a post-processor that adds a call log through a JDK dynamic proxy, which is how Spring applies cross-cutting behavior to an interface:</p>\n<pre><code class=\"language-java\">interface Greeter { String greet(String name); }\n\nclass EnglishGreeter implements Greeter {\n    public String greet(String name) { return \"Hello, \" + name; }\n}\n\nclass Welcome {\n    private final Greeter greeter;\n    Welcome(Greeter greeter) { this.greeter = greeter; }\n    String message() { return greeter.greet(\"Ada\"); }\n}\n\npublic class MiniDemo {\n\n    public static void main(String[] args) {\n        MiniContainer container = new MiniContainer();\n        container.register(Greeter.class, EnglishGreeter.class);\n        container.register(Welcome.class, Welcome.class);\n\n        container.addPostProcessor(bean -&gt; {\n            Class&lt;?&gt;[] interfaces = bean.getClass().getInterfaces();\n            if (interfaces.length == 0) return bean;\n            return Proxy.newProxyInstance(bean.getClass().getClassLoader(), interfaces,\n                (proxy, method, methodArgs) -&gt; {\n                    System.out.println(\"-&gt; \" + method.getName());\n                    return method.invoke(bean, methodArgs);\n                });\n        });\n\n        container.refresh();\n        System.out.println(container.get(Welcome.class).message());\n        System.out.println(container.get(Greeter.class).getClass().getName());\n    }\n}</code></pre>\n<p>The output shows <code>-&gt; greet</code>, then <code>Hello, Ada</code>, and the last line prints a class named like <code>jdk.proxy1.$Proxy0</code>, not <code>EnglishGreeter</code>. That is the whole trick behind <code>@Transactional</code>, in miniature: the object that was injected into <code>Welcome</code> is the wrapper, and a call on <code>this</code> inside <code>EnglishGreeter</code> would never print the arrow. Try adding a second method on <code>EnglishGreeter</code> that calls <code>greet</code>, call it through the proxy, and watch the inner call go unlogged. The container also detects the cycle if you make two beans need each other, which is the behavior of constructor injection described earlier, in one <code>if</code>.</p>\n<h2>Watch a real bean being born</h2>\n<p>Spring exposes every step of the sequence as a hook, so you can print the life of a bean in a real context. This class implements most of them, and a <code>BeanPostProcessor</code> logs the steps that surround initialization:</p>\n<pre><code class=\"language-java\">@Component\nclass Audited implements BeanNameAware, InitializingBean, DisposableBean {\n\n    Audited() { System.out.println(\"1. constructor\"); }\n\n    @Autowired\n    void setDependency(Clock clock) { System.out.println(\"2. injection of \" + clock.getClass().getSimpleName()); }\n\n    @Override\n    public void setBeanName(String name) { System.out.println(\"3. aware of its own name: \" + name); }\n\n    @PostConstruct\n    void postConstruct() { System.out.println(\"5. @PostConstruct\"); }\n\n    @Override\n    public void afterPropertiesSet() { System.out.println(\"6. afterPropertiesSet\"); }\n\n    @PreDestroy\n    void preDestroy() { System.out.println(\"9. @PreDestroy\"); }\n\n    @Override\n    public void destroy() { System.out.println(\"10. destroy\"); }\n}\n\n@Component\nclass Tracer implements BeanPostProcessor {\n\n    @Override\n    public Object postProcessBeforeInitialization(Object bean, String name) {\n        if (bean instanceof Audited) System.out.println(\"4. postProcessBeforeInitialization\");\n        return bean;\n    }\n\n    @Override\n    public Object postProcessAfterInitialization(Object bean, String name) {\n        if (bean instanceof Audited) System.out.println(\"7. postProcessAfterInitialization (proxy goes here)\");\n        return bean;\n    }\n}</code></pre>\n<p>Run it in any context that has a <code>Clock</code> bean, and the numbered lines appear in the order of the lifecycle list. Two details are worth noticing. <code>@PostConstruct</code> runs before <code>afterPropertiesSet</code>, which is the order of the list above, and both run after every dependency is injected, so the bean can use them. And the <code>BeanPostProcessor</code> is itself a bean that the container must create first, which is why a post-processor with a dependency on a normal service causes the \"not eligible for getting processed by all BeanPostProcessors\" message: the service was created before the processors were ready, so it went without its proxy. Declare processors as <code>static</code> <code>@Bean</code> methods and give them as few dependencies as you can.</p>\n<h2>Ways to fix self-invocation, with their costs</h2>\n<p>The self-invocation trap appears in the <code>InvoiceService</code> example, and there are four honest ways out. The cleanest is to move the second method to another bean, so the call crosses a proxy:</p>\n<pre><code class=\"language-java\">@Service\nclass InvoiceService {\n\n    private final InvoiceWriter writer;\n\n    InvoiceService(InvoiceWriter writer) { this.writer = writer; }\n\n    @Transactional\n    public void create(Invoice invoice) {\n        writer.save(invoice);                 // goes through the writer's proxy\n    }\n}\n\n@Service\nclass InvoiceWriter {\n\n    @Transactional(propagation = Propagation.REQUIRES_NEW)\n    public void save(Invoice invoice) { /* own transaction */ }\n}</code></pre>\n<p>This costs one extra class and it makes the boundary visible, which is usually the right trade. The second way is to manage the transaction programmatically where the method is, with <code>TransactionTemplate</code>, which has no proxy to bypass:</p>\n<pre><code class=\"language-java\">@Service\nclass InvoiceService {\n\n    private final TransactionTemplate requiresNew;\n\n    InvoiceService(PlatformTransactionManager manager) {\n        this.requiresNew = new TransactionTemplate(manager);\n        this.requiresNew.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);\n    }\n\n    public void create(Invoice invoice) {\n        requiresNew.executeWithoutResult(status -&gt; save(invoice));\n    }\n\n    private void save(Invoice invoice) { /* inside its own transaction */ }\n}</code></pre>\n<p>The third is to inject the bean into itself with <code>@Lazy</code> and call through the reference, which works and reads as a trick. The fourth is <code>AopContext.currentProxy()</code> with <code>@EnableAspectJAutoProxy(exposeProxy = true)</code>, which ties your class to Spring's AOP API and is the one to avoid. Use the first when the method is a real unit of work, and the second when the transaction logic is part of one method's flow. A related trap is a <code>private</code> or <code>final</code> method with <code>@Transactional</code>: the annotation is silently ignored, because a CGLIB subclass cannot override it.</p>\n<h2><code>@Configuration</code> classes and the proxy you did not know about</h2>\n<p>Another proxy sits in plain sight. A class annotated with <code>@Configuration</code> is subclassed by CGLIB so that calls between its <code>@Bean</code> methods return the container's singleton, not a new object:</p>\n<pre><code class=\"language-java\">@Configuration\nclass AppConfig {\n\n    @Bean\n    Clock clock() { return Clock.systemUTC(); }\n\n    @Bean\n    PriceCalculator calculator() {\n        return new PriceCalculator(clock());     // returns the singleton Clock bean, not a new one\n    }\n\n    @Bean\n    ReportBuilder reports() {\n        return new ReportBuilder(clock());       // the same Clock again\n    }\n}</code></pre>\n<p>If you change the annotation to <code>@Configuration(proxyBeanMethods = false)</code>, or to <code>@Component</code>, which is \"lite mode\", <code>clock()</code> becomes an ordinary method call and both beans get different <code>Clock</code> instances. That can be faster at startup and is correct only when the methods do not call each other. In lite mode, take the dependency as a parameter instead, which is clearer in both modes:</p>\n<pre><code class=\"language-java\">@Bean\nPriceCalculator calculator(Clock clock) {\n    return new PriceCalculator(clock);\n}</code></pre>\n<p>Spring Boot's own auto-configurations use <code>proxyBeanMethods = false</code> for exactly this reason, and a reasonable rule for application code is to take parameters and never call <code>@Bean</code> methods from each other.</p>\n<h2>Ordering, laziness and the events around startup</h2>\n<p>Singletons are created in dependency order, and between unrelated beans the order is not a contract. When one bean needs another to exist first without holding a reference to it, say so with <code>@DependsOn</code>. When creation is expensive and rarely needed, mark it lazy, and the cost moves from startup to the first use:</p>\n<pre><code class=\"language-java\">@Component\n@Lazy\nclass PdfRenderer { /* loads fonts, takes a second to build */ }\n\n@Component\n@DependsOn(\"schemaMigrator\")\nclass CatalogCache { /* must not read the database before the migrations ran */ }</code></pre>\n<p>Lazy initialization for the whole application, with <code>spring.main.lazy-initialization=true</code>, speeds startup and moves wiring errors from boot to the first request that touches the bean, which defeats the early failure that is one of the container's best features. Use it for developer machines and tests, and be careful in production. To run code once everything is ready, listen for the right event and do not use a <code>@PostConstruct</code> in a bean that others depend on:</p>\n<pre><code class=\"language-java\">@Component\nclass WarmUp {\n\n    @EventListener(ApplicationReadyEvent.class)\n    void onReady() {\n        // all singletons exist, the web server is accepting connections\n    }\n\n    @EventListener(ContextClosedEvent.class)\n    void onClose() {\n        // the container is shutting down, before beans are destroyed\n    }\n}</code></pre>\n<p><code>ContextRefreshedEvent</code> fires when the context is fully initialized, <code>ApplicationReadyEvent</code> (Spring Boot) fires after the application runners have completed, and the order matters when a health check must not report ready until the warm-up has finished.</p>\n<h2>Breaking a cycle you cannot redesign</h2>\n<p>Constructor cycles are a design signal, and the right fix is to extract the shared part into a third bean that both depend on. When the redesign is not possible this week, <code>@Lazy</code> on one injection point defers the real dependency behind a proxy and lets the container start:</p>\n<pre><code class=\"language-java\">@Service\nclass OrderService {\n\n    private final NotificationService notifications;\n\n    OrderService(@Lazy NotificationService notifications) {\n        this.notifications = notifications;\n    }\n}</code></pre>\n<p>The proxy resolves the real bean on its first method call. The cycle still exists in the design, so leave a comment with the ticket for the redesign, since a deferred cycle tends to become permanent. Spring Boot disables circular references by default for a reason: a cycle is a sign that two classes know too much about each other.</p>\n<h2>Test the container's behavior, not only your classes</h2>\n<p>Wiring is behavior, and Spring Boot provides a runner that builds small contexts fast, with no web server. It is the right tool to check conditional beans, qualifiers and property binding:</p>\n<pre><code class=\"language-java\">class PricingConfigTest {\n\n    private final ApplicationContextRunner runner = new ApplicationContextRunner()\n        .withUserConfiguration(PricingConfig.class);\n\n    @Test\n    void usesTheFlatRateByDefault() {\n        runner.run(context -&gt; assertThat(context).hasSingleBean(FlatRate.class));\n    }\n\n    @Test\n    void switchesToTieredPricingWhenEnabled() {\n        runner.withPropertyValues(\"shop.pricing.mode=tiered\")\n              .run(context -&gt; {\n                  assertThat(context).hasSingleBean(TieredRate.class);\n                  assertThat(context).doesNotHaveBean(FlatRate.class);\n              });\n    }\n\n    @Test\n    void failsWithAClearMessageWhenTheCurrencyIsMissing() {\n        runner.withPropertyValues(\"shop.pricing.mode=tiered\", \"shop.currency=\")\n              .run(context -&gt; assertThat(context).hasFailed());\n    }\n}</code></pre>\n<p>Each test builds a context in milliseconds, and the third one asserts that a bad configuration refuses to start, which protects the \"fail at startup\" promise. Use it for every auto-configuration or conditional bean you write.</p>\n<h2>Inspect a running container</h2>\n<p>When you do not own the code, ask the context. In a Spring Boot application, three tools cover almost every question about what exists and why:</p>\n<pre><code class=\"language-bash\">curl -s localhost:8080/actuator/beans | jq '.contexts.application.beans | keys | length'\ncurl -s localhost:8080/actuator/conditions | jq '.contexts.application.negativeMatches | keys | .[0:5]'</code></pre>\n<pre><code class=\"language-properties\">logging.level.org.springframework.beans.factory.support.DefaultListableBeanFactory=DEBUG</code></pre>\n<p>The <code>beans</code> endpoint lists every bean with its scope, type and dependencies. <code>conditions</code> shows why an auto-configuration did not apply, and the debug log of the bean factory prints each singleton as it is created, which finds the one that takes four seconds. Expose these endpoints only in a development profile or behind authentication, since they describe your application's internals.</p>\n<h2>Ahead-of-time processing changes the \"when\"</h2>\n<p>The model in this guide says the container reads definitions at startup, and that was accurate for years. With ahead-of-time (AOT) processing, used for GraalVM native images and optionally for faster JVM startup, Spring computes the bean definitions at build time and generates plain Java code that registers them. The practical effects are the same ones Quarkus users know: conditions on beans are evaluated at build time, so a profile or property that decides which bean exists must be known when the application is built, and reflection that Spring cannot see must be declared with hints (<code>@RegisterReflectionForBinding</code> and <code>RuntimeHints</code>). If you stay on the JVM with a normal build, none of this applies, and the container behaves as described above.</p>\n<h2>A method for diagnosing a container problem</h2>\n<p>When a Spring application behaves in a way the code does not explain, resist the urge to try fixes. Work through four questions in order, and most problems are located by the second.</p>\n<p>First, is this the object the code appears to use? Print the class of the injected bean. A name such as <code>InvoiceService$$SpringCGLIB$$0</code> or <code>$Proxy53</code> says the call goes through a proxy, and a plain class name says it does not, so an annotation on it cannot be working. Second, did the call cross the proxy? A call from another bean does, and a call on <code>this</code> does not. Third, which definition won? If there are two candidates, find out which one the container picked and why, with the <code>beans</code> endpoint or by asking for the bean by name. Fourth, when was it created, and with what? A singleton that holds a value from startup will never see a later change, and a bean created before its post-processors were ready has no proxy at all.</p>\n<p>The answers are usually dull. A <code>@Transactional</code> method was <code>private</code>. A bean was defined twice, once by scanning and once by an explicit method. A request-scoped value was injected into a singleton, so the first user's data was kept for everyone. Each of these is a statement about the container's model, and none of them needs a debugger once the model is clear. The reason to spend an afternoon with the mini container above is that the model then stays in your head, and the next surprise takes minutes.</p>\n<p>Two habits keep surprises rare. Put behavior that depends on a proxy, such as transactions and caching, at the boundary of a bean that other beans call, and keep the internals of a class free of annotations that need the proxy. And treat the startup log as a result. A context that starts cleanly with every bean accounted for is a fact worth having, and a test that builds it, as in the context runner example, turns that fact into something a build can check on every commit.</p>\n<h2>Where this model stops</h2>\n<p>The container model above is for a Spring application context on the JVM. It does not describe ahead-of-time processing, where Spring Framework 6 and later can compute the bean definitions at build time for native images, and some of the dynamic features above are restricted. If your service is on that path, the <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot guide</a> covers the practical limits, and <a href=\"/library/quarkus-spring-developers\">Quarkus</a> is built around the same idea from the start.</p>","date_published":"2026-11-14T04:25:31+00:00","tags":["Spring Framework"]},{"id":"https://javahacks.dev/library/spring-mvc-rest-api-guide-building","url":"https://javahacks.dev/library/spring-mvc-rest-api-guide-building","title":"Spring MVC REST API Guide to Building Clean Endpoints","summary":"Build a clean Spring MVC REST API: records at the edge, validation, one error format, pagination, caching headers, security, testing and what to avoid.","content_html":"<p>A REST API is a contract with people you cannot ask. Clients compile against your field names, retry on your status codes and parse your error bodies, so every inconsistency you ship becomes a workaround in someone else's code. Spring MVC gives you enough rope to build an API that is consistent or one that is not, and the difference is a handful of conventions applied from the first endpoint: one shape per resource, one place for errors, explicit status codes, and tests that read like the contract.</p>\n<p>This guide builds a small task-tracking API on Spring Boot 4 and Java 25, one decision at a time. It covers controllers and records, validation, a single error format, creating and updating resources, pagination and filtering, caching headers, CORS, security, versioning and testing, and ends with the mistakes that cost the most time. The examples use Spring MVC (the servlet stack); <a href=\"/library/rest-vs-graphql-vs-grpc-java\">reactive and virtual-thread alternatives</a> and the API style question are covered elsewhere. If you have not built a Boot project yet, start with <a href=\"/library/spring-boot-guide-first-project-production\">the Spring Boot guide</a>. The snippets were not compiled in a build for this post, so treat them as reviewed examples and compile them against your versions; the annotations used are stable across Spring Framework 6 and 7.</p>\n<h2>How a request reaches your controller</h2>\n<p>You write less glue when you know what runs. A request reaches the <code>DispatcherServlet</code>, which asks the handler mappings which method handles that URL and verb, runs interceptors, resolves the method's arguments (path variables, query parameters, the JSON body through an <code>HttpMessageConverter</code>), calls your method, and writes the return value back through a converter. Exceptions go to the exception resolvers. Every error named in this guide is one of those stages complaining: a <code>405</code> is the mapping stage, a <code>415</code> is the converter stage, a <code>400</code> on a body is deserialization, and a <code>400</code> with field details is argument validation. The detailed flow, with filters and interceptors, is in <a href=\"/library/spring-mvc-works-handles-request-filter\">how Spring MVC handles a request</a>.</p>\n<h2>Design the URLs before the code</h2>\n<p>Decide the resource vocabulary first, because URLs are the hardest thing to change later. A workable convention:</p>\n<table><thead><tr><th>Operation</th><th>Request</th><th>Success</th><th>Notes</th></tr></thead><tbody><tr><td>List tasks</td><td><code>GET /api/tasks?status=OPEN&amp;page=0&amp;size=20</code></td><td><code>200</code></td><td>Filters and paging in the query string</td></tr><tr><td>Get one</td><td><code>GET /api/tasks/{id}</code></td><td><code>200</code></td><td><code>404</code> when absent</td></tr><tr><td>Create</td><td><code>POST /api/tasks</code></td><td><code>201</code> and <code>Location</code></td><td>Server assigns the id</td></tr><tr><td>Replace or update</td><td><code>PUT /api/tasks/{id}</code></td><td><code>200</code> or <code>204</code></td><td>Idempotent</td></tr><tr><td>Partial update</td><td><code>PATCH /api/tasks/{id}</code></td><td><code>200</code></td><td>Only the fields sent</td></tr><tr><td>Delete</td><td><code>DELETE /api/tasks/{id}</code></td><td><code>204</code></td><td><code>404</code> or <code>204</code> when already gone, pick one and document it</td></tr><tr><td>An action that is not CRUD</td><td><code>POST /api/tasks/{id}/complete</code></td><td><code>200</code></td><td>A verb as a sub-resource, honestly named</td></tr></tbody></table>\n<p>Use plural nouns, lowercase and hyphens, and no verbs in the path except for actions. Do not put the version in the resource name or the database id format in the contract unless you mean to keep it forever. The reasoning behind these rules is in <a href=\"/library/rest-api-url-design-resource-urls\">resource URL design</a> and the wider set of rules in <a href=\"/library/rest-api-design-rules-java-teams\">REST API design rules for Java teams</a>.</p>\n<h2>One controller per resource, records at the edge</h2>\n<p>The API's request and response shapes should be their own types, separate from the JPA entity. Java records make that cheap: immutable, no boilerplate, and a constructor Jackson can use.</p>\n<pre data-filename=\"src/main/java/dev/javahacks/tasks/TaskDtos.java\"><code class=\"language-java\">import jakarta.validation.constraints.FutureOrPresent;\nimport jakarta.validation.constraints.NotBlank;\nimport jakarta.validation.constraints.Size;\nimport java.time.Instant;\nimport java.time.LocalDate;\n\npublic final class TaskDtos {\n\n    private TaskDtos() { }\n\n    public record CreateTask(\n            @NotBlank @Size(max = 120) String title,\n            @Size(max = 2000) String description,\n            @FutureOrPresent LocalDate dueDate) { }\n\n    public record UpdateTask(\n            @NotBlank @Size(max = 120) String title,\n            @Size(max = 2000) String description,\n            LocalDate dueDate,\n            TaskStatus status) { }\n\n    public record TaskView(\n            long id,\n            String title,\n            String description,\n            LocalDate dueDate,\n            TaskStatus status,\n            Instant createdAt) { }\n}</code></pre>\n<p>The create type carries only what a client may set. There is no <code>id</code>, no <code>createdAt</code> and no <code>status</code>, so a client cannot choose them, which also closes the mass-assignment hole where a request sets a field it should not. The view type is what comes back. Keep three types even when they look similar today: they diverge the first time you add an internal column.</p>\n<p>The controller maps HTTP to service calls and does nothing else:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/tasks/TaskController.java\"><code class=\"language-java\">import dev.javahacks.tasks.TaskDtos.CreateTask;\nimport dev.javahacks.tasks.TaskDtos.TaskView;\nimport dev.javahacks.tasks.TaskDtos.UpdateTask;\nimport jakarta.validation.Valid;\nimport java.net.URI;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.PutMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\n@RestController\n@RequestMapping(\"/api/tasks\")\nclass TaskController {\n\n    private final TaskService tasks;\n\n    TaskController(TaskService tasks) {\n        this.tasks = tasks;\n    }\n\n    @GetMapping\n    Page&lt;TaskView&gt; list(@RequestParam(required = false) TaskStatus status, Pageable page) {\n        return tasks.list(status, page);\n    }\n\n    @GetMapping(\"/{id}\")\n    TaskView get(@PathVariable long id) {\n        return tasks.get(id);\n    }\n\n    @PostMapping\n    ResponseEntity&lt;TaskView&gt; create(@Valid @RequestBody CreateTask request) {\n        TaskView created = tasks.create(request);\n        URI location = ServletUriComponentsBuilder.fromCurrentRequest()\n                .path(\"/{id}\").buildAndExpand(created.id()).toUri();\n        return ResponseEntity.created(location).body(created);\n    }\n\n    @PutMapping(\"/{id}\")\n    TaskView update(@PathVariable long id, @Valid @RequestBody UpdateTask request) {\n        return tasks.update(id, request);\n    }\n\n    @DeleteMapping(\"/{id}\")\n    ResponseEntity&lt;Void&gt; delete(@PathVariable long id) {\n        tasks.delete(id);\n        return ResponseEntity.noContent().build();\n    }\n}</code></pre>\n<p>Notice the choices. Methods that always succeed with <code>200</code> return the body directly. Methods whose status varies, <code>create</code> and <code>delete</code>, return <code>ResponseEntity</code>. <code>@Valid</code> on the body parameter triggers validation before the method runs. <code>Pageable</code> is resolved from <code>page</code>, <code>size</code> and <code>sort</code> query parameters automatically when Spring Data's web support is on, which it is in Boot. And the controller has no <code>try</code> or <code>catch</code>: errors are thrown, and one class handles them.</p>\n<h2>Let the service decide what is missing</h2>\n<p>A controller asking \"is it null?\" for every lookup is a controller doing the service's job. Make the service throw a domain exception, and map the exception to HTTP in one place:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/tasks/TaskService.java\"><code class=\"language-java\">import dev.javahacks.tasks.TaskDtos.CreateTask;\nimport dev.javahacks.tasks.TaskDtos.TaskView;\nimport dev.javahacks.tasks.TaskDtos.UpdateTask;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\n@Service\n@Transactional(readOnly = true)\nclass TaskService {\n\n    private final TaskRepository repository;\n\n    TaskService(TaskRepository repository) {\n        this.repository = repository;\n    }\n\n    Page&lt;TaskView&gt; list(TaskStatus status, Pageable page) {\n        Page&lt;Task&gt; found = status == null ? repository.findAll(page) : repository.findByStatus(status, page);\n        return found.map(TaskService::toView);\n    }\n\n    TaskView get(long id) {\n        return toView(find(id));\n    }\n\n    @Transactional\n    TaskView create(CreateTask request) {\n        Task task = new Task(request.title(), request.description(), request.dueDate());\n        return toView(repository.save(task));\n    }\n\n    @Transactional\n    TaskView update(long id, UpdateTask request) {\n        Task task = find(id);\n        task.change(request.title(), request.description(), request.dueDate(), request.status());\n        return toView(task);\n    }\n\n    @Transactional\n    void delete(long id) {\n        repository.delete(find(id));\n    }\n\n    private Task find(long id) {\n        return repository.findById(id).orElseThrow(() -&gt; new TaskNotFoundException(id));\n    }\n\n    private static TaskView toView(Task t) {\n        return new TaskView(t.getId(), t.getTitle(), t.getDescription(), t.getDueDate(),\n                t.getStatus(), t.getCreatedAt());\n    }\n}</code></pre>\n<p>The <code>update</code> method has no <code>save</code> call. Inside a transaction, a managed entity's changes are flushed on commit, so changing the fields is enough. The mapping to a view happens inside the service, where the entity is still attached; mapping in the controller would touch lazy associations outside the transaction. See <a href=\"#never-serialize-entities-directly\">never serialize entities directly</a> below.</p>\n<h2>One advice class for every error</h2>\n<p>Without a plan, each failure produces a different body: a stack trace from the default handler, a bare <code>{\"error\": \"...\"}</code> from a hand-written one, an HTML page from a servlet error. Pick one format and produce it everywhere. The standard is RFC 9457 Problem Details, and Spring has <code>ProblemDetail</code> for it:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/tasks/ApiExceptionHandler.java\"><code class=\"language-java\">import java.net.URI;\nimport java.util.List;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ProblemDetail;\nimport org.springframework.web.bind.MethodArgumentNotValidException;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\n\n@RestControllerAdvice\nclass ApiExceptionHandler {\n\n    @ExceptionHandler(TaskNotFoundException.class)\n    ProblemDetail notFound(TaskNotFoundException ex) {\n        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());\n        p.setTitle(\"Task not found\");\n        p.setType(URI.create(\"https://api.example.com/problems/task-not-found\"));\n        return p;\n    }\n\n    @ExceptionHandler(MethodArgumentNotValidException.class)\n    ProblemDetail invalid(MethodArgumentNotValidException ex) {\n        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, \"Request validation failed\");\n        p.setTitle(\"Invalid request\");\n        List&lt;FieldIssue&gt; issues = ex.getBindingResult().getFieldErrors().stream()\n                .map(f -&gt; new FieldIssue(f.getField(), f.getDefaultMessage()))\n                .toList();\n        p.setProperty(\"errors\", issues);\n        return p;\n    }\n\n    record FieldIssue(String field, String message) { }\n}</code></pre>\n<p>A failed validation now answers like this:</p>\n<pre><code class=\"language-text\">HTTP/1.1 400\nContent-Type: application/problem+json\n\n{\"type\":\"about:blank\",\"title\":\"Invalid request\",\"status\":400,\"detail\":\"Request validation failed\",\n \"instance\":\"/api/tasks\",\"errors\":[{\"field\":\"title\",\"message\":\"must not be blank\"}]}</code></pre>\n<p>The shape is identical for every error, so a client writes one handler. A few rules for the content: <code>detail</code> is for humans and never includes a stack trace or SQL; <code>type</code> is a stable URI clients can switch on, and the machine-readable part is the status plus <code>type</code> plus your <code>errors</code> extension. Spring can also generate Problem Details for its own exceptions (<code>405</code>, <code>415</code>, missing parameters) when you set <code>spring.mvc.problemdetails.enabled=true</code>, which gives the framework's errors the same shape without code. Add a catch-all <code>@ExceptionHandler(Exception.class)</code> that logs with a correlation id and returns a generic <code>500</code>, so an unexpected failure never leaks internals. The individual exceptions, with causes, are covered in <a href=\"/library/methodargumentnotvalidexception-fix-return-clean-errors\">MethodArgumentNotValidException</a>, <a href=\"/library/missingservletrequestparameterexception-fix-spring-mvc\">missing request parameters</a>, <a href=\"/library/httpmessagenotreadableexception-fix-json-parse-error\">unreadable JSON</a>, <a href=\"/library/httpmediatypenotsupportedexception-fix-spring-mvc\">415 errors</a> and <a href=\"/library/405-method-not-allowed-spring-mvc\">405 errors</a>.</p>\n<h2>Status codes that tell the truth</h2>\n<p>Clients branch on status codes, so use the precise ones:</p>\n<table><thead><tr><th>Situation</th><th>Status</th></tr></thead><tbody><tr><td>Read or update succeeded</td><td><code>200</code></td></tr><tr><td>Created</td><td><code>201</code> with <code>Location</code></td></tr><tr><td>Succeeded, nothing to return</td><td><code>204</code></td></tr><tr><td>Malformed JSON or a failed validation</td><td><code>400</code></td></tr><tr><td>Not authenticated</td><td><code>401</code></td></tr><tr><td>Authenticated, not allowed</td><td><code>403</code></td></tr><tr><td>No such resource</td><td><code>404</code></td></tr><tr><td>Wrong verb for the URL</td><td><code>405</code></td></tr><tr><td>Conflict with current state (duplicate, stale version)</td><td><code>409</code></td></tr><tr><td>Unsupported <code>Content-Type</code></td><td><code>415</code></td></tr><tr><td>Semantically wrong but well-formed</td><td><code>422</code> (or <code>400</code>, choose one and keep it)</td></tr><tr><td>Too many requests</td><td><code>429</code> with <code>Retry-After</code></td></tr><tr><td>Unexpected failure</td><td><code>500</code></td></tr></tbody></table>\n<p>Two that teams get wrong: returning <code>200</code> with <code>{\"success\": false}</code> (it defeats every HTTP-aware tool, from caches to monitoring), and using <code>404</code> for authorization failures to hide that a resource exists, which is a legitimate choice only when you decide it deliberately.</p>\n<h2>Pagination and filtering</h2>\n<p>Returning a <code>Page</code> from a controller serializes Spring Data's internal structure, which includes fields you did not choose and which has changed shape between versions. Prefer your own envelope:</p>\n<pre><code class=\"language-java\">public record PageResponse&lt;T&gt;(java.util.List&lt;T&gt; items, int page, int size, long total) {\n\n    public static &lt;T&gt; PageResponse&lt;T&gt; of(org.springframework.data.domain.Page&lt;T&gt; p) {\n        return new PageResponse&lt;&gt;(p.getContent(), p.getNumber(), p.getSize(), p.getTotalElements());\n    }\n}</code></pre>\n<p>Cap the page size so a client cannot ask for a million rows. In Boot that is configuration:</p>\n<pre><code class=\"language-properties\">spring.data.web.pageable.default-page-size=20\nspring.data.web.pageable.max-page-size=100</code></pre>\n<p>Offset paging (<code>page</code> and <code>size</code>) is simple and fine for small to medium tables. For large or fast-changing data, offset paging gets slow and skips or repeats rows when data changes between requests; use keyset (cursor) paging there, as in <a href=\"/library/cursor-pagination-spring-use-boot-api\">cursor pagination</a>. Whitelist sortable fields instead of passing <code>sort</code> straight to the database, or a client can sort by a column with no index.</p>\n<h2>Validation beyond the body</h2>\n<p><code>@Valid</code> handles request bodies. For query and path parameters, put constraints on the parameter and add <code>@Validated</code> to the class. Since Spring Framework 6.1 the framework validates method parameters itself and throws <code>HandlerMethodValidationException</code>, which you handle like the one above:</p>\n<pre><code class=\"language-java\">@GetMapping(\"/search\")\nList&lt;TaskView&gt; search(@RequestParam @Size(min = 2, max = 50) String q) {\n    return tasks.search(q);\n}</code></pre>\n<p>Cross-field rules belong in a class-level constraint or in the service. Business rules, such as \"a completed task cannot be reopened after 30 days\", belong in the service as well, and throw an exception mapped to <code>409</code>. A validator annotation is the wrong tool for anything that needs the database.</p>\n<h2>Caching and conditional requests</h2>\n<p>GET responses can be cached, and conditional requests save bandwidth. The cheapest option is an ETag computed from the response body:</p>\n<pre><code class=\"language-java\">@Bean\nFilterRegistrationBean&lt;ShallowEtagHeaderFilter&gt; etag() {\n    var bean = new FilterRegistrationBean&lt;&gt;(new ShallowEtagHeaderFilter());\n    bean.addUrlPatterns(\"/api/*\");\n    return bean;\n}</code></pre>\n<p>A client that sends <code>If-None-Match</code> with the previous ETag gets a <code>304</code> with no body. The server still does the work of building the response, so this saves transfer, not computation. For computation savings, return explicit headers from the controller with <code>ResponseEntity.ok().cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePublic())</code> where the data allows it, and handle <code>If-Match</code> on updates to prevent lost writes. The full set is in <a href=\"/library/etag-conditional-request-spring-add-requests\">ETag and conditional requests</a> and HTTP cache headers.</p>\n<h2>CORS without guessing</h2>\n<p>A browser app on another origin triggers a preflight <code>OPTIONS</code> request, and an API without CORS configuration answers it with an error the browser reports as a CORS failure. Configure it in one place, with explicit origins:</p>\n<pre><code class=\"language-java\">@Bean\nWebMvcConfigurer cors() {\n    return new WebMvcConfigurer() {\n        @Override\n        public void addCorsMappings(CorsRegistry registry) {\n            registry.addMapping(\"/api/**\")\n                    .allowedOrigins(\"https://app.example.com\")\n                    .allowedMethods(\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\")\n                    .allowedHeaders(\"Authorization\", \"Content-Type\")\n                    .maxAge(3600);\n        }\n    };\n}</code></pre>\n<p>If Spring Security is on the classpath, CORS must also be enabled in the security filter chain, or the preflight is rejected before MVC sees it. Never combine <code>allowedOrigins(\"*\")</code> with credentials. The common failures are in <a href=\"/library/spring-boot-cors-error-fix-errors\">Spring Boot CORS errors</a>.</p>\n<h2>Never serialize entities directly</h2>\n<p>It is tempting to return the JPA entity from the controller. It works for a day. Then a lazy collection is touched outside the transaction and throws, a bidirectional relationship (<code>Task</code> to <code>Project</code> and back) recurses until the stack overflows, the entity gains an internal column that now appears in the API, and a client depends on a field you meant to rename. The cure is the one already used: map to a view record inside the service. If you want to see the recursion failure and its fixes, it is covered here. Mapping by hand is a few lines per type and trivially debuggable; a mapping library is fine once you have many types, as long as the mapping runs inside the transaction.</p>\n<h2>Securing the API</h2>\n<p>An API that returns data for users needs authentication and authorization, and Spring Security is the standard answer. A minimal resource-server setup that accepts JWT bearer tokens:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/config/SecurityConfig.java\"><code class=\"language-java\">import org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.security.config.Customizer;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.web.SecurityFilterChain;\n\n@Configuration\nclass SecurityConfig {\n\n    @Bean\n    SecurityFilterChain api(HttpSecurity http) throws Exception {\n        http\n            .csrf(csrf -&gt; csrf.disable())                         // stateless bearer-token API\n            .authorizeHttpRequests(auth -&gt; auth\n                .requestMatchers(HttpMethod.GET, \"/api/tasks/**\").hasAuthority(\"SCOPE_tasks:read\")\n                .requestMatchers(\"/api/tasks/**\").hasAuthority(\"SCOPE_tasks:write\")\n                .anyRequest().denyAll())\n            .oauth2ResourceServer(oauth -&gt; oauth.jwt(Customizer.withDefaults()));\n        return http.build();\n    }\n}</code></pre>\n<p>Two points. Disabling CSRF protection is correct only for APIs that authenticate with a header token and never with a cookie; a cookie-authenticated API needs CSRF protection. And <code>anyRequest().denyAll()</code> makes new endpoints closed by default, which is the safer failure. Authorization on the data matters as much as on the route: a user who may read tasks must still only read their own, so filter by the authenticated principal in the service and test it.</p>\n<h2>Versioning</h2>\n<p>Plan for change, because the first breaking change comes sooner than expected. Additive changes (a new optional field, a new endpoint) need no version: tell clients to ignore unknown fields. Breaking changes (renaming a field, changing a type) need a way to coexist. The common options are a path prefix (<code>/api/v2/tasks</code>), a header, or a media type. Spring Framework 7 adds first-class API versioning to the MVC mapping annotations, so a version can be declared on the handler instead of duplicated in paths; check the reference for your release for the exact configuration. Whichever you choose, keep the old version running for a stated period and measure its traffic before removing it.</p>\n<h2>Partial updates with PATCH</h2>\n<p><code>PUT</code> replaces a resource, so the client must send every field. Clients that edit one field want <code>PATCH</code>, and the question is how to say \"leave this alone\" versus \"set this to null\". A Java record cannot tell a missing JSON field from an explicit <code>null</code>, so a naive <code>PatchTask(String title, String description)</code> clears the description whenever the client omits it. Two sound options exist.</p>\n<p>The first is JSON Merge Patch (RFC 7396): the body is a JSON object, present fields overwrite, <code>null</code> removes, absent fields are untouched. Read the body as a <code>JsonNode</code> and apply it onto the current view:</p>\n<pre><code class=\"language-java\">@PatchMapping(path = \"/{id}\", consumes = \"application/merge-patch+json\")\nTaskView patch(@PathVariable long id, @RequestBody JsonNode patch) {\n    return tasks.patch(id, patch);\n}</code></pre>\n<pre><code class=\"language-java\">@Transactional\nTaskView patch(long id, JsonNode patch) {\n    Task task = find(id);\n    if (patch.has(\"title\")) task.rename(patch.get(\"title\").asText());\n    if (patch.has(\"description\")) {\n        task.describe(patch.get(\"description\").isNull() ? null : patch.get(\"description\").asText());\n    }\n    if (patch.has(\"status\")) task.moveTo(TaskStatus.valueOf(patch.get(\"status\").asText()));\n    return toView(task);\n}</code></pre>\n<p>Validate inside the entity methods (<code>rename</code> rejects blank), because the body bypasses bean validation. The second option is to avoid generic patching: expose the real operations as sub-resources (<code>POST /api/tasks/{id}/complete</code>, <code>PUT /api/tasks/{id}/assignee</code>). Small, named operations are easier to authorize, audit and test than a patch that can change anything. We prefer them when the operations are few and have rules.</p>\n<h2>Actions that are not CRUD, and slow work</h2>\n<p>Some operations do not map onto a resource update: <code>complete</code>, <code>archive</code>, <code>export</code>. Model them as a <code>POST</code> to an action path and keep the verb honest in the name. When the work takes longer than a request should, do not hold the connection. Accept the job, answer <code>202 Accepted</code> with a link to a status resource, and let the client poll:</p>\n<pre><code class=\"language-java\">@PostMapping(\"/exports\")\nResponseEntity&lt;Void&gt; startExport(@RequestBody ExportRequest request) {\n    String jobId = exports.submit(request);                 // returns immediately, runs elsewhere\n    URI status = URI.create(\"/api/exports/\" + jobId);\n    return ResponseEntity.accepted().location(status).build();\n}\n\n@GetMapping(\"/exports/{jobId}\")\nResponseEntity&lt;ExportStatus&gt; status(@PathVariable String jobId) {\n    ExportStatus s = exports.status(jobId);\n    return s.done()\n        ? ResponseEntity.status(HttpStatus.SEE_OTHER).location(s.resultUri()).build()\n        : ResponseEntity.ok(s);\n}</code></pre>\n<p>While running, the status endpoint returns <code>200</code> with a state and progress; when finished it redirects with <code>303</code> to the result. A client that follows redirects needs no special handling. Keep jobs in a table, not in memory, so a restart does not lose them.</p>\n<h2>Safe retries with idempotency keys</h2>\n<p><code>GET</code>, <code>PUT</code> and <code>DELETE</code> are idempotent by definition: repeating them has the same effect. <code>POST</code> is not, and networks fail after the server has acted but before the client hears. The client retries, and the order is created twice. The fix is an <code>Idempotency-Key</code> header: the client sends a unique value per logical operation, and the server stores the response keyed by it and replays the stored response on a repeat.</p>\n<pre><code class=\"language-java\">@PostMapping\nResponseEntity&lt;TaskView&gt; create(@RequestHeader(name = \"Idempotency-Key\", required = false) String key,\n                                @Valid @RequestBody CreateTask request) {\n    return idempotency.execute(key, () -&gt; {\n        TaskView created = tasks.create(request);\n        return ResponseEntity.created(locationOf(created)).body(created);\n    });\n}</code></pre>\n<p>The <code>idempotency</code> component inserts the key into a table with a unique constraint before doing the work and stores the result afterwards; a concurrent duplicate hits the constraint and waits or returns <code>409</code>. The mechanics, including the expiry of old keys, are in <a href=\"/library/idempotency-key-spring-boot-implement-keys\">idempotent REST endpoints</a>. Apply it to the endpoints where a duplicate costs money or creates visible duplicates, and not to every <code>POST</code>.</p>\n<h2>Content negotiation</h2>\n<p>Spring picks a response format from the <code>Accept</code> header. JSON is the default with Jackson on the classpath. To offer a second representation, such as CSV for an export, declare it on the mapping and write a converter or return the bytes yourself:</p>\n<pre><code class=\"language-java\">@GetMapping(path = \"/export\", produces = \"text/csv\")\nResponseEntity&lt;byte[]&gt; exportCsv() {\n    String csv = tasks.toCsv();\n    return ResponseEntity.ok()\n            .header(\"Content-Disposition\", \"attachment; filename=\\\"tasks.csv\\\"\")\n            .body(csv.getBytes(java.nio.charset.StandardCharsets.UTF_8));\n}</code></pre>\n<p>A request with <code>Accept: application/json</code> for that path gets a <code>406 Not Acceptable</code>, which is the correct answer. Prefer the <code>Accept</code> header over a <code>.csv</code> suffix or a <code>?format=</code> parameter; Spring Framework 6 disabled suffix matching by default for good reason.</p>\n<h2>Uploads and large responses</h2>\n<p>File uploads arrive as <code>multipart/form-data</code>. Bind them with <code>MultipartFile</code> and set explicit limits, because the defaults are generous:</p>\n<pre><code class=\"language-properties\">spring.servlet.multipart.max-file-size=5MB\nspring.servlet.multipart.max-request-size=6MB</code></pre>\n<pre><code class=\"language-java\">@PostMapping(path = \"/{id}/attachments\", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)\nResponseEntity&lt;Void&gt; attach(@PathVariable long id, @RequestParam(\"file\") MultipartFile file) throws IOException {\n    if (file.isEmpty() || !List.of(\"image/png\", \"application/pdf\").contains(file.getContentType())) {\n        throw new ResponseStatusException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, \"Only PNG and PDF are accepted\");\n    }\n    attachments.store(id, file.getOriginalFilename(), file.getInputStream());\n    return ResponseEntity.noContent().build();\n}</code></pre>\n<p>Never use <code>getOriginalFilename()</code> as a path: generate your own storage name, or you have a path traversal bug. A client-supplied <code>Content-Type</code> is a claim and not a fact; sniff the bytes if it matters. For large downloads, return a <code>StreamingResponseBody</code> or a <code>Resource</code> so the response is written in chunks, and the heap does not hold the whole file.</p>\n<h2>Observability from day one</h2>\n<p>An API you cannot see is an API you cannot fix. Three things pay for themselves immediately.</p>\n<p><strong>A request id.</strong> Generate one per request in a filter, put it in the logging context (<code>MDC</code>) and echo it in a response header. Every log line for that request then carries the id, and a user's complaint becomes a single search. Spring Boot 3.2 and later add trace and span ids to the MDC when Micrometer tracing is on the classpath.</p>\n<p><strong>Metrics.</strong> Actuator with Micrometer records request counts and latency per route and status with no code: <code>http.server.requests</code>. Alert on the rate of <code>5xx</code> and on the p95 and p99 latency of the busiest routes, not on averages.</p>\n<p><strong>Structured logs.</strong> One JSON object per line, with the request id, the route and the outcome, lets you query logs by field. Spring Boot 3.4 added built-in structured logging formats (<code>logging.structured.format.console=ecs</code>).</p>\n<pre><code class=\"language-properties\">management.endpoints.web.exposure.include=health,info,metrics,prometheus\nmanagement.endpoint.health.probes.enabled=true\nlogging.structured.format.console=ecs</code></pre>\n<p>Keep Actuator on a separate management port or behind authentication, since <code>/actuator/env</code> and <code>/actuator/heapdump</code> are sensitive.</p>\n<h2>Document the API from the code</h2>\n<p>Clients need documentation that cannot drift from the implementation. The usual route is an OpenAPI description generated from the controllers and served beside the app, or the reverse, an OpenAPI file written first and server stubs generated from it. Either way, the description is checked in or published by CI, and a contract test compares behavior to it. The tools and trade-offs of generating from code or from a spec are in <a href=\"/library/openapi-3-java-document-api\">OpenAPI 3 for Java</a>. Documentation should include the error format, the pagination envelope, the authentication scheme and examples of a failing request, because those are what integrators read first.</p>\n<h2>Rate limiting and abuse</h2>\n<p>A public API will be abused sooner or later, by a bug in a client loop as often as by an attacker. Put rate limiting at the edge (an API gateway or reverse proxy) so excess traffic never reaches the JVM, and answer with <code>429</code> and a <code>Retry-After</code> header. Inside the application, bound the expensive things directly: maximum page size, maximum request body size (<code>server.tomcat.max-swallow-size</code>, <code>spring.servlet.multipart.*</code>), maximum number of items in a bulk request and a timeout on outbound calls. A <code>POST /api/tasks/bulk</code> that accepts a list should reject more than, say, 500 items with <code>413</code> or <code>400</code> and a message that states the limit.</p>\n<h2>A project layout that scales</h2>\n<p>A layout that keeps each concern findable, with packages by feature and not by layer:</p>\n<pre><code class=\"language-text\">src/main/java/dev/javahacks/\n  tasks/\n    TaskController.java      # HTTP only\n    TaskService.java         # rules, transactions\n    TaskRepository.java      # persistence\n    Task.java                # entity\n    TaskDtos.java            # request and response records\n    TaskNotFoundException.java\n  config/\n    SecurityConfig.java\n    WebConfig.java\n  common/\n    ApiExceptionHandler.java</code></pre>\n<p>Package-private classes (as in the examples above, with no <code>public</code>) mean other features cannot reach into the task internals; only the controller's HTTP surface is public in effect. When the second feature arrives, copy the shape, not the code, and move shared code to <code>common</code> only when three features need it.</p>\n<h2>Test the contract, not the class</h2>\n<p>A good API test sends HTTP and asserts on the response a client would see. <code>MockMvc</code> does this without starting a server, and a <code>@WebMvcTest</code> loads only the web layer. The service is mocked, so the test checks mapping, validation and error format:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/tasks/TaskControllerTest.java\"><code class=\"language-java\">import static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.when;\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;\n\nimport dev.javahacks.tasks.TaskDtos.CreateTask;\nimport dev.javahacks.tasks.TaskDtos.TaskView;\nimport java.time.Instant;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.MediaType;\nimport org.springframework.test.context.bean.override.mockito.MockitoBean;\nimport org.springframework.test.web.servlet.MockMvc;\n\n// annotated with @WebMvcTest(TaskController.class); the import package moved in Boot 4, let the IDE add it\nclass TaskControllerTest {\n\n    @Autowired MockMvc mvc;\n    @MockitoBean TaskService service;\n\n    @Test\n    void createReturns201WithLocation() throws Exception {\n        when(service.create(any(CreateTask.class))).thenReturn(\n                new TaskView(7, \"Write tests\", null, null, TaskStatus.OPEN, Instant.parse(\"2026-01-01T00:00:00Z\")));\n\n        mvc.perform(post(\"/api/tasks\")\n                        .contentType(MediaType.APPLICATION_JSON)\n                        .content(\"{\\\"title\\\":\\\"Write tests\\\"}\"))\n           .andExpect(status().isCreated())\n           .andExpect(header().string(\"Location\", \"http://localhost/api/tasks/7\"))\n           .andExpect(jsonPath(\"$.id\").value(7));\n    }\n\n    @Test\n    void blankTitleIsRejectedWithProblemDetail() throws Exception {\n        mvc.perform(post(\"/api/tasks\")\n                        .contentType(MediaType.APPLICATION_JSON)\n                        .content(\"{\\\"title\\\":\\\"\\\"}\"))\n           .andExpect(status().isBadRequest())\n           .andExpect(jsonPath(\"$.errors[0].field\").value(\"title\"));\n    }\n\n    @Test\n    void unknownTaskIsA404() throws Exception {\n        when(service.get(99)).thenThrow(new TaskNotFoundException(99));\n        mvc.perform(get(\"/api/tasks/99\")).andExpect(status().isNotFound());\n    }\n}</code></pre>\n<p>Three layers make a healthy suite: unit tests for business rules in the service, web-layer tests like the one above for the HTTP contract, and a few <code>@SpringBootTest</code> integration tests with a real database through Testcontainers for the wiring, transactions and queries. The contract tests are cheap and catch the regressions clients feel: a renamed field, a changed status, a different error shape.</p>\n<h2>Mistakes that cost the most time</h2>\n<table><thead><tr><th>Mistake</th><th>Effect</th><th>Fix</th></tr></thead><tbody><tr><td>Returning entities</td><td>Lazy-loading errors, infinite recursion, leaked columns</td><td>Records as views, mapped in the service</td></tr><tr><td>No global error handler</td><td>Different bodies for different failures, stack traces in responses</td><td>One <code>@RestControllerAdvice</code> with <code>ProblemDetail</code></td></tr><tr><td><code>200</code> with an error in the body</td><td>Monitoring and caches cannot see failures</td><td>Use real status codes</td></tr><tr><td>Unbounded list endpoints</td><td>One request loads the table</td><td>Default and maximum page size</td></tr><tr><td>Accepting the entity as the request body</td><td>Clients set <code>id</code>, <code>createdAt</code>, roles</td><td>Separate request records</td></tr><tr><td>Business logic in controllers</td><td>Untestable without HTTP</td><td>Put rules in services</td></tr><tr><td>Catching exceptions in each controller</td><td>Inconsistent errors</td><td>Throw, and handle in the advice</td></tr><tr><td>Disabling CSRF on a cookie-authenticated API</td><td>Cross-site request forgery</td><td>Disable only for header-token APIs</td></tr></tbody></table>\n<h2>Where this design stops</h2>\n<p>This is the request-and-response API style, which fits most CRUD-shaped services. If clients need to ask for exactly the fields they want across many resources, GraphQL may fit better; if the callers are internal services that need streaming and strict contracts, look at gRPC. Both trade-offs are laid out in <a href=\"/library/rest-vs-graphql-vs-grpc-java\">REST against GraphQL and gRPC</a>. Very high-concurrency, I/O-bound services may prefer virtual threads or a reactive stack, which changes how you write handlers but not the contract conventions above. The authoritative references are the <a href=\"https://docs.spring.io/spring-framework/reference/web/webmvc.html\">Spring MVC reference</a> and <a href=\"https://www.rfc-editor.org/rfc/rfc9457\">RFC 9457</a> for the error format.</p>","date_published":"2026-11-14T04:24:31+00:00","tags":["Spring MVC"]},{"id":"https://javahacks.dev/library/hibernate-jpa-guide-without-surprises","url":"https://javahacks.dev/library/hibernate-jpa-guide-without-surprises","title":"Hibernate JPA Guide to Mapping Fetching and N Plus 1","summary":"Map entities, control fetching and remove the N plus 1 problem in Hibernate 7, with the settings and habits that keep JPA predictable.","content_html":"<p>The <a href=\"https://hibernate.org/orm/documentation/\">Hibernate ORM documentation</a> and the <a href=\"https://jakarta.ee/specifications/persistence/\">Jakarta Persistence specification</a> are the primary sources for everything below. Hibernate does what you ask, and the trouble is how much of what it does is an implicit default. A <code>@ManyToOne</code> is eager unless you say otherwise, a collection loads one row at a time unless you fetch it, and a session lives as long as your transaction, which may be shorter than you think. This guide fixes those defaults for Hibernate 7 on PostgreSQL 17 and shows where each failure appears. It assumes Spring Boot, as described in <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a>.</p>\n<p>If you want the vocabulary first, <a href=\"/library/hibernate-jpa-are-they-relate\">Hibernate and JPA, and how they relate</a> separates the specification from the implementation.</p>\n<h2>Map an entity with explicit intent</h2>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/Order.java\"><code class=\"language-java\">@Entity\n@Table(name = \"orders\")\npublic class Order {\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private Long id;\n\n    @Version\n    private long version;\n\n    @ManyToOne(fetch = FetchType.LAZY, optional = false)\n    @JoinColumn(name = \"customer_id\")\n    private Customer customer;\n\n    @OneToMany(mappedBy = \"order\", cascade = CascadeType.ALL, orphanRemoval = true)\n    private List&lt;OrderLine&gt; lines = new ArrayList&lt;&gt;();\n\n    protected Order() {}   // required by JPA\n\n    public void addLine(OrderLine line) {\n        lines.add(line);\n        line.setOrder(this);\n    }\n}</code></pre>\n<p>Three choices here do real work. <code>fetch = LAZY</code> on the <code>@ManyToOne</code> overrides the JPA default, which is <code>EAGER</code> for to-one associations. <code>@Version</code> adds optimistic locking for free. The helper <code>addLine</code> keeps both sides of the bidirectional association in step, which is the part people forget and then wonder why the foreign key is null.</p>\n<p>An entity is not a record. Hibernate creates proxy subclasses and sets fields by reflection, so keep entities as ordinary mutable classes with a protected no-argument constructor.</p>\n<h2>Fetching: ask for what you need</h2>\n<p>Lazy mapping is only half the answer. The other half is loading what a use case needs, once. There are three tools:</p>\n<table><thead><tr><th>Tool</th><th>Use it when</th><th>Cost</th></tr></thead><tbody><tr><td><code>JOIN FETCH</code> in JPQL</td><td>One association, a known query</td><td>Cartesian row growth with collections</td></tr><tr><td><code>@EntityGraph</code></td><td>A repository method needs a different shape</td><td>Same SQL as a fetch join, declared separately</td></tr><tr><td>DTO projection</td><td>A read-only screen or API response</td><td>No managed entities, no lazy surprises</td></tr></tbody></table>\n<pre><code class=\"language-java\">public interface OrderRepository extends JpaRepository&lt;Order, Long&gt; {\n\n    @Query(\"select o from Order o join fetch o.customer where o.id = :id\")\n    Optional&lt;Order&gt; findWithCustomer(@Param(\"id\") Long id);\n\n    @Query(\"select new dev.javahacks.shop.OrderSummary(o.id, c.name, o.total) \" +\n           \"from Order o join o.customer c where o.status = :status\")\n    List&lt;OrderSummary&gt; summaries(@Param(\"status\") OrderStatus status);\n}</code></pre>\n<p>Fetching two collections in one query fails with [<code>MultipleBagFetchException</code>](/library/multiplebagfetchexception-fix-fetch-joins-batching), and the fix is to fetch one collection per query or to batch. Never \"fix\" it by changing a <code>List</code> to a <code>Set</code> without understanding that the join still multiplies rows.</p>\n<h2>Find N plus 1 in a test</h2>\n<p>N plus 1 is one query for a list and one more per row for an association. It hides in development with ten rows and appears in production with ten thousand. Count statements in a test:</p>\n<pre><code class=\"language-java\">@DataJpaTest\nclass OrderQueriesTest {\n\n    @Autowired EntityManager em;\n\n    @Test\n    void listingOrdersDoesNotQueryPerRow() {\n        Statistics stats = em.getEntityManagerFactory()\n                .unwrap(SessionFactory.class).getStatistics();\n        stats.setStatisticsEnabled(true);\n        stats.clear();\n\n        em.createQuery(\"select o from Order o\", Order.class).getResultList()\n          .forEach(o -&gt; o.getCustomer().getName());\n\n        assertThat(stats.getPrepareStatementCount()).isEqualTo(1);\n    }\n}</code></pre>\n<p>With a lazy <code>customer</code> and no fetch join, the count is <code>1 + number of distinct customers</code>, and the test fails. Add <code>join fetch o.customer</code> and it passes. The full walkthrough, including batch fetching with <code>hibernate.default_batch_fetch_size</code>, is in <a href=\"/library/hibernate-n-plus-1-problem-fix\">fixing the Hibernate N plus 1 problem</a>.</p>\n<h2>Sessions, transactions and the lazy exception</h2>\n<p>A lazy association loads through the session that loaded its owner. When the session closes, touching the association throws:</p>\n<pre><code class=\"language-text\">org.hibernate.LazyInitializationException: could not initialize proxy [dev.javahacks.shop.Customer#1] - no Session</code></pre>\n<p>In Spring, the session lives for the transaction. Set <code>spring.jpa.open-in-view=false</code> and load what the use case needs inside the service method, so the failure shows up in a test. [Fixing <code>LazyInitializationException</code>](/library/lazyinitializationexception-fix-spring-boot-hibernate) lists the options in order of preference.</p>\n<h2>Saving: persist, merge and the detached trap</h2>\n<p>An entity is transient (new), managed (in a session), detached (session closed) or removed. <code>save()</code> on a Spring Data repository calls <code>persist</code> for a new entity and <code>merge</code> for an existing id. Passing a detached entity where a new one is expected raises [<code>detached entity passed to persist</code>](/library/detached-entity-passed-persist-fix-spring), and referencing an unsaved entity in an association raises [<code>TransientPropertyValueException</code>](/library/transientpropertyvalueexception-fix-save-spring-data).</p>\n<h2>Concurrent edits</h2>\n<p>Two users edit the same order. Without a version column the second save overwrites the first. With <code>@Version</code>, Hibernate adds <code>where version = ?</code> to the update, and the loser gets an optimistic locking failure that you turn into a <code>409</code>. See [<code>StaleObjectStateException</code> and locking failures](/library/staleobjectstateexception-fix-locking-failures) for retry and message handling.</p>\n<h2>Schema belongs to migrations</h2>\n<p><code>spring.jpa.hibernate.ddl-auto=update</code> is a development convenience that cannot rename a column, drop one safely or reproduce a production schema. Use Flyway or Liquibase for changes and set <code>ddl-auto=validate</code> so Hibernate refuses to start if the mapping and the schema disagree.</p>\n<h2>Identifiers: the generation strategy changes what Hibernate can batch</h2>\n<p>The mapping above used <code>GenerationType.IDENTITY</code>, which hands the choice of key to the database column. It is the simplest and has one cost that matters for writes: Hibernate must run the <code>insert</code> immediately to learn the id, so it cannot group inserts into a JDBC batch. A sequence lets Hibernate reserve a block of ids in advance and send many inserts at once:</p>\n<pre><code class=\"language-java\">@Id\n@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"order_seq\")\n@SequenceGenerator(name = \"order_seq\", sequenceName = \"order_seq\", allocationSize = 50)\nprivate Long id;</code></pre>\n<p>The <code>allocationSize</code> must match the <code>INCREMENT BY</code> of the sequence in your migration, or two application instances will hand out overlapping ids:</p>\n<pre><code class=\"language-sql\">create sequence order_seq start with 1 increment by 50;</code></pre>\n<p>PostgreSQL and Oracle have sequences natively. MySQL does not, and on MySQL <code>IDENTITY</code> is the practical choice, with the batching limit that comes with it. If you must generate ids in the application, a UUID version 7 (time-ordered) keeps the index friendly, where a random version 4 scatters inserts across the whole B-tree:</p>\n<pre><code class=\"language-java\">@Id\n@GeneratedValue\n@UuidGenerator(style = UuidGenerator.Style.VERSION_7)\nprivate UUID id;</code></pre>\n<p>Check the Hibernate release you use for the generator styles it offers, because this annotation has grown with each major version.</p>\n<h2>Mapping details that cause quiet bugs</h2>\n<p>Several defaults are legal and wrong. Enums are mapped by ordinal unless you say otherwise, so inserting a value in the middle of the enum silently reinterprets every stored row:</p>\n<pre><code class=\"language-java\">@Enumerated(EnumType.STRING)\n@Column(nullable = false, length = 20)\nprivate OrderStatus status;</code></pre>\n<p>Use <code>Instant</code> or <code>OffsetDateTime</code> for points in time, and keep the database column in UTC (<code>timestamp with time zone</code> on PostgreSQL). <code>LocalDateTime</code> has no zone, so it is correct only if every writer agrees on one, and nothing enforces that agreement. Money is <code>BigDecimal</code> with an explicit precision and scale:</p>\n<pre><code class=\"language-java\">@Column(nullable = false, precision = 19, scale = 4)\nprivate BigDecimal total;</code></pre>\n<p>A value that belongs to an entity and has no identity of its own is an embeddable. Hibernate 6.2 and later accept a record:</p>\n<pre><code class=\"language-java\">@Embeddable\npublic record Address(String street, String city, String postalCode, String country) {}\n\n@Entity\npublic class Customer {\n    @Id @GeneratedValue private Long id;\n\n    @Embedded\n    private Address billingAddress;\n\n    @AttributeOverrides({\n        @AttributeOverride(name = \"street\", column = @Column(name = \"shipping_street\")),\n        @AttributeOverride(name = \"city\", column = @Column(name = \"shipping_city\")),\n        @AttributeOverride(name = \"postalCode\", column = @Column(name = \"shipping_postal_code\")),\n        @AttributeOverride(name = \"country\", column = @Column(name = \"shipping_country\"))\n    })\n    @Embedded\n    private Address shippingAddress;\n}</code></pre>\n<p>Two embedded values of the same type need column overrides, as above, or the mapping fails at startup with a duplicate column error. For a column that needs custom conversion, such as a type-safe wrapper around a string, write an <code>AttributeConverter</code> with <code>@Converter(autoApply = true)</code> and the mapping stays clean.</p>\n<h2>Equality and collections: choose a <code>Set</code>, write <code>equals</code> carefully</h2>\n<p>An entity's <code>equals</code> and <code>hashCode</code> are among the most argued subjects in JPA, and the workable answer is short. The id is null until the entity is persisted, so an implementation based on the id alone breaks a <code>HashSet</code> that held the entity before and after saving. A business key (an email, an ISBN, an order number) works when one exists. When none does, use the id with a stable hash code:</p>\n<pre><code class=\"language-java\">@Entity\npublic class OrderLine {\n\n    @Id @GeneratedValue\n    private Long id;\n\n    @Override\n    public boolean equals(Object other) {\n        if (this == other) return true;\n        if (!(other instanceof OrderLine line)) return false;\n        return id != null &amp;&amp; id.equals(line.id);\n    }\n\n    @Override\n    public int hashCode() {\n        return getClass().hashCode();\n    }\n}</code></pre>\n<p>The constant hash code looks wrong and is correct for this purpose: it stays the same before and after the id is assigned, at the cost of every line of one class sharing a bucket. For collections of a few dozen children, that cost is invisible. Do not put a lazy association or a collection into <code>equals</code>, <code>hashCode</code> or <code>toString</code>, because each of those can trigger a load or recurse through a bidirectional mapping.</p>\n<p>On the collection type itself: a <code>List</code> without an order column is a \"bag\" in Hibernate terms, and bags are what make <code>MultipleBagFetchException</code> appear when you fetch two at once. A <code>Set</code> is the honest type for a collection with no meaningful order, and <code>@OrderColumn</code> on a <code>List</code> makes the order persistent, at the price of extra updates when you insert in the middle.</p>\n<h2>Fetching collections and paging at the same time</h2>\n<p>A fetch join on a collection multiplies parent rows, which breaks <code>LIMIT</code>. Hibernate warns when you try:</p>\n<pre><code class=\"language-text\">HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory</code></pre>\n<p>That line means the database returned every row and Hibernate cut the page in memory, which is a memory problem waiting for a large table. Turn the warning into an error in development so that it cannot reach production:</p>\n<pre><code class=\"language-yaml\">spring:\n  jpa:\n    properties:\n      hibernate:\n        query:\n          fail_on_pagination_over_collection_fetch: true</code></pre>\n<p>The correct pattern uses two queries. Page the parent ids first, then fetch the data for just those ids:</p>\n<pre><code class=\"language-java\">public interface OrderRepository extends JpaRepository&lt;Order, Long&gt; {\n\n    @Query(\"select o.id from Order o where o.status = :status order by o.createdAt desc\")\n    List&lt;Long&gt; pageIds(@Param(\"status\") OrderStatus status, Pageable page);\n\n    @Query(\"select distinct o from Order o left join fetch o.lines where o.id in :ids order by o.createdAt desc\")\n    List&lt;Order&gt; withLines(@Param(\"ids\") List&lt;Long&gt; ids);\n}</code></pre>\n<pre><code class=\"language-java\">@Transactional(readOnly = true)\npublic List&lt;Order&gt; latest(OrderStatus status, int size) {\n    List&lt;Long&gt; ids = orders.pageIds(status, PageRequest.of(0, size));\n    return ids.isEmpty() ? List.of() : orders.withLines(ids);\n}</code></pre>\n<p>Each query is simple and indexed, and the page size is enforced by the database. When the screen needs two collections, run a third query for the second one in the same style, and let the persistence context stitch the results together, since the entities are the same instances in one session.</p>\n<h2>Batch fetching as a safety net</h2>\n<p>Even careful code leaves some lazy loads. <code>hibernate.default_batch_fetch_size</code> turns the remaining N plus 1 into N divided by the batch size:</p>\n<pre><code class=\"language-yaml\">spring:\n  jpa:\n    properties:\n      hibernate:\n        default_batch_fetch_size: 32</code></pre>\n<p>With a value of 32, loading the lines of 100 orders issues four queries with an <code>in</code> list instead of 100. It is a safety net rather than a replacement for fetch joins, because it still issues more statements than one join would. Set it globally, and use <code>@BatchSize</code> on a single association when only one needs it.</p>\n<h2>Writing efficiently</h2>\n<p>Reads get the attention, and writes cause a surprising share of the load. Two settings and one habit cover most of it:</p>\n<pre><code class=\"language-yaml\">spring:\n  jpa:\n    properties:\n      hibernate:\n        jdbc:\n          batch_size: 50\n        order_inserts: true\n        order_updates: true</code></pre>\n<p><code>batch_size</code> groups inserts and updates into JDBC batches, and the <code>order_</code> flags sort statements by entity so that batches can form. The habit is to flush and clear in a loop when you process many entities, since the persistence context keeps every entity you touch:</p>\n<pre><code class=\"language-java\">@Transactional\npublic void importOrders(Iterator&lt;NewOrder&gt; source) {\n    int count = 0;\n    while (source.hasNext()) {\n        em.persist(Order.from(source.next()));\n        if (++count % 50 == 0) {\n            em.flush();\n            em.clear();\n        }\n    }\n}</code></pre>\n<p>Without <code>clear()</code>, an import of a million rows grows the session until the heap runs out, and dirty checking slows as it grows. For an update that touches many rows by a rule, such as closing every order older than a year, skip entities and use one statement:</p>\n<pre><code class=\"language-java\">@Modifying\n@Query(\"update Order o set o.status = 'CLOSED' where o.status = 'SHIPPED' and o.createdAt &lt; :before\")\nint closeOlderThan(@Param(\"before\") Instant before);</code></pre>\n<p>A bulk update bypasses the persistence context, so entities already loaded in the session do not see the change, and the <code>@Version</code> column is not bumped unless you do it in the query. Run it at the start of a transaction, or clear the context afterwards.</p>\n<h2>Locking: optimistic by default, pessimistic where it pays</h2>\n<p>The <code>@Version</code> column from the first example covers the common case of two people editing one record. When the conflict is frequent and the work is cheap to repeat, retry:</p>\n<pre><code class=\"language-java\">@Retryable(retryFor = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)\n@Transactional\npublic void rename(long id, String name) {\n    Customer c = customers.findById(id).orElseThrow();\n    c.rename(name);\n}</code></pre>\n<p>Put the retry outside the transaction, so that each attempt gets a fresh one, which means the annotated method must be called through the proxy and from a bean that is not itself in the same transaction. When correctness depends on one writer at a time, such as allocating the last unit of stock, lock the row:</p>\n<pre><code class=\"language-java\">public interface StockRepository extends JpaRepository&lt;Stock, Long&gt; {\n\n    @Lock(LockModeType.PESSIMISTIC_WRITE)\n    @QueryHints(@QueryHint(name = \"jakarta.persistence.lock.timeout\", value = \"2000\"))\n    @Query(\"select s from Stock s where s.sku = :sku\")\n    Optional&lt;Stock&gt; lockBySku(@Param(\"sku\") String sku);\n}</code></pre>\n<p>The query becomes <code>select ... for update</code>, and the timeout turns an endless wait into an exception you can report. For a work queue where many workers each want one free row, the hint <code>jakarta.persistence.lock.timeout</code> set to <code>-2</code> requests <code>SKIP LOCKED</code> on databases that support it, so workers pass over rows another transaction holds. Check your database and Hibernate version for the exact behavior before relying on it.</p>\n<h2>Caching: what Hibernate holds for you</h2>\n<p>The first-level cache is the persistence context itself: within one session, loading the same id twice returns the same instance and runs one query. It is why <code>findById</code> in a loop is cheaper than it looks and why a long session slows down. The second-level cache is optional and lives across sessions. It pays for reference data that is read often and changed rarely, such as countries or tax tables:</p>\n<pre><code class=\"language-java\">@Entity\n@Cacheable\n@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)\npublic class Country {\n    @Id private String code;\n    private String name;\n}</code></pre>\n<pre><code class=\"language-yaml\">spring:\n  jpa:\n    properties:\n      hibernate:\n        cache:\n          use_second_level_cache: true\n          region.factory_class: jcache\n      jakarta.persistence.sharedCache.mode: ENABLE_SELECTIVE</code></pre>\n<p>You also need a JCache provider such as Ehcache or Caffeine on the classpath. Be cautious with the query cache, which stores result ids and is invalidated on any write to the tables involved, so it helps only on near-static data. A cache is a consistency risk across several application instances unless it is a distributed one, so measure the gain before you accept the risk. If the same data can be served from the application's own cache with an explicit expiry, that is often easier to reason about.</p>\n<h2>Auditing and soft deletes</h2>\n<p>Two requirements appear in nearly every business application, and both have small, standard answers. Spring Data auditing fills in who and when:</p>\n<pre><code class=\"language-java\">@MappedSuperclass\n@EntityListeners(AuditingEntityListener.class)\npublic abstract class Auditable {\n\n    @CreatedDate @Column(updatable = false)\n    private Instant createdAt;\n\n    @LastModifiedDate\n    private Instant updatedAt;\n\n    @CreatedBy @Column(updatable = false)\n    private String createdBy;\n}</code></pre>\n<p>Enable it with <code>@EnableJpaAuditing</code> and provide an <code>AuditorAware&lt;String&gt;</code> bean that returns the current user. Soft deletion is built into recent Hibernate releases:</p>\n<pre><code class=\"language-java\">@Entity\n@SoftDelete\npublic class Document {\n    @Id @GeneratedValue private Long id;\n    private String title;\n}</code></pre>\n<p>With <code>@SoftDelete</code>, <code>delete</code> marks the row and every query excludes it, without a hand-written <code>where deleted = false</code> on each repository method. Think about unique constraints before you adopt it, since a deleted row still holds its unique value, and about whether regulations require real deletion, in which case soft delete is the wrong tool.</p>\n<h2>Tests that protect the mapping</h2>\n<p>A JPA mapping fails at runtime in ways a compiler cannot see, so a few tests are worth more than usual. Run them against the real database engine, which Testcontainers makes easy:</p>\n<pre><code class=\"language-java\">@DataJpaTest\n@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)\n@Testcontainers\nclass MappingTest {\n\n    @Container\n    @ServiceConnection\n    static PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;(\"postgres:17\");\n\n    @Autowired TestEntityManager em;\n\n    @Test\n    void orderRoundTripsWithLinesAndVersion() {\n        Customer customer = em.persist(new Customer(\"Ada\"));\n        Order order = new Order(customer);\n        order.addLine(new OrderLine(\"sku-1\", 2));\n        em.persistAndFlush(order);\n        em.clear();\n\n        Order loaded = em.find(Order.class, order.getId());\n\n        assertEquals(1, loaded.getLines().size());\n        assertEquals(0L, loaded.getVersion());\n    }\n}</code></pre>\n<p>With <code>ddl-auto=validate</code> and your migrations applied to the container, this test fails at startup if a column is missing or mistyped, which catches most mapping drift before a deployment does. Combine it with the statement-counting test from the N plus 1 section for every query that serves a list.</p>\n<h2>Read the SQL while you develop</h2>\n<p>Hibernate's job is to write SQL for you, so read it. In development, print the statements with their parameter values, formatted, and keep it off in production:</p>\n<pre><code class=\"language-yaml\">spring:\n  jpa:\n    show-sql: false\nlogging:\n  level:\n    org.hibernate.SQL: DEBUG\n    org.hibernate.orm.jdbc.bind: TRACE</code></pre>\n<p>The <code>org.hibernate.SQL</code> logger prints each statement through your normal logging, and the bind logger prints the parameters. Scan the output for three signs of trouble: the same statement repeated many times with different ids (N plus 1), a <code>select</code> on a table you did not expect to touch (an eager association), and an <code>update</code> you did not ask for (dirty checking flushing a change you made by accident, such as a setter that normalizes a value on read).</p>\n<h2>Exceptions and what they usually mean</h2>\n<table><thead><tr><th>Exception</th><th>Usual cause</th><th>First move</th></tr></thead><tbody><tr><td><code>LazyInitializationException</code></td><td>Association read after the session closed</td><td>Load it in the use case, or return a DTO</td></tr><tr><td><code>MultipleBagFetchException</code></td><td>Two <code>List</code> collections in one fetch join</td><td>Fetch one per query</td></tr><tr><td><code>StaleObjectStateException</code></td><td>Optimistic lock lost</td><td>Reload and retry, or return 409</td></tr><tr><td><code>DataIntegrityViolationException</code></td><td>A constraint rejected the write</td><td>Read the nested SQL state and constraint name</td></tr><tr><td><code>TransientObjectException</code></td><td>Association points at an unsaved entity</td><td>Save the child first, or use cascade</td></tr><tr><td><code>NonUniqueResultException</code></td><td>A query expected one row and found several</td><td>Fix the query or the data, never <code>LIMIT 1</code> to silence it</td></tr><tr><td><code>QueryException: could not resolve property</code></td><td>Typo in JPQL</td><td>Compile-time checking with the JPA metamodel</td></tr></tbody></table>\n<p>Treat the table as a map, and follow it with the post that covers each case in depth. Most Hibernate trouble is one of the first three, and the first three are the three decisions listed at the top of this guide.</p>\n<h2>A short review checklist for a JPA pull request</h2>\n<p>When a pull request touches an entity or a repository, five questions find most of the trouble before it ships. Does every association say how it is fetched, and is each to-one association lazy? Does each list endpoint have a test that counts statements, so a new association cannot quietly add one query per row? Is the transaction boundary on the service method that runs the use case, with nothing slow, such as a remote call, inside it? Did the schema change arrive as a migration, and does the mapping still validate against it? And if two users can edit the record, is there a version column and a response for the conflict?</p>\n<p>The answers take a minute to read in a diff, and a reviewer who asks them every time teaches the team the three decisions at the top of this guide without a single lecture. Keep the list in the repository with the pull request template, and add a line to it each time a production issue traces back to something it did not ask.</p>\n<h2>What Hibernate does not suit</h2>\n<p>Hibernate is a good fit for a domain model that is read and written in units of aggregates. It is a poor fit for reporting queries over millions of rows, bulk updates and anything where you think in sets: write those in SQL through <code>JdbcClient</code> or a native query, and keep the object model for the writes. If the database is the center of your design, <a href=\"/library/jdbc-tutorial-connect-database-step-step\">JDBC</a> is the honest tool, and nothing stops you using both in one service.</p>","date_published":"2026-11-14T04:23:31+00:00","tags":["Hibernate"]},{"id":"https://javahacks.dev/library/quarkus-spring-developers","url":"https://javahacks.dev/library/quarkus-spring-developers","title":"Quarkus for Spring Developers and What Changes in Practice","summary":"Map what you know from Spring Boot to Quarkus 3, from CDI and RESTEasy to dev mode and native images, and see where the models really differ.","content_html":"<p>If you know Spring Boot, you already know about three quarters of Quarkus; the <a href=\"https://quarkus.io/guides/\">Quarkus guides</a> cover the rest. The annotations are different, the ideas are the same, and the real divide is when the work happens. This guide maps the Spring concepts you use to their Quarkus 3 equivalents on JDK 25, then spends its time on the differences that cause trouble. It builds on <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a> and <a href=\"/library/spring-container-works-really\">how the Spring container works</a>, so those make good side-by-side reading.</p>\n<p>For a first project from scratch, <a href=\"/library/quarkus-tutorial-beginners-zero-rest-api\">the Quarkus tutorial for beginners</a> goes step by step. This page is for people who want the comparison.</p>\n<h2>The same ideas under different names</h2>\n<table><thead><tr><th>You use in Spring Boot</th><th>You use in Quarkus</th></tr></thead><tbody><tr><td><code>@Component</code>, <code>@Service</code>, <code>@Autowired</code></td><td><code>@ApplicationScoped</code>, <code>@Inject</code> (CDI)</td></tr><tr><td><code>@RestController</code>, <code>@GetMapping</code></td><td><code>@Path</code>, <code>@GET</code> (JAX-RS, Quarkus REST)</td></tr><tr><td>Spring Data JPA repository</td><td>Panache repository or active record</td></tr><tr><td><code>@ConfigurationProperties</code></td><td><code>@ConfigMapping</code></td></tr><tr><td>Actuator</td><td>SmallRye Health and Micrometer extensions</td></tr><tr><td>Spring Boot DevTools restart</td><td>Dev mode (<code>quarkus dev</code>)</td></tr><tr><td><code>@SpringBootTest</code></td><td><code>@QuarkusTest</code></td></tr><tr><td>Testcontainers wiring</td><td>Dev Services</td></tr></tbody></table>\n<p>A resource looks familiar:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/hello/GreetingResource.java\"><code class=\"language-java\">@Path(\"/hello\")\npublic class GreetingResource {\n\n    @Inject\n    GreetingService service;\n\n    @GET\n    @Produces(MediaType.TEXT_PLAIN)\n    public String hello(@QueryParam(\"name\") @DefaultValue(\"world\") String name) {\n        return service.greet(name);\n    }\n}</code></pre>\n<p>Injection is by type with <code>@Inject</code>, and CDI scopes replace Spring's. <code>@ApplicationScoped</code> is the singleton-like default for services, and it is proxied, so the same self-invocation caveat applies as in Spring. If two beans match a type, the error is the CDI one, covered in <a href=\"/library/quarkus-unsatisfied-dependency-fix-ambiguous-beans\">Quarkus unsatisfied dependency and ambiguous beans</a>.</p>\n<h2>Build time is the difference</h2>\n<p>Spring reads annotations, creates proxies and wires beans when the application starts. Quarkus does that work while building, and the running application contains the result. This is why startup is quick and memory is low, and why <a href=\"/library/quarkus-build-time-processing-explained\">Quarkus build time processing</a> is the post to read when something behaves oddly. The consequences:</p>\n<ul><li>Properties marked \"fixed at build time\" cannot change at runtime. Setting them with an environment variable on a deployed jar has no effect. The configuration reference marks each one.</li><li>Anything discovered by reflection at runtime must be known to the build. Extensions register their own classes; your own classes used reflectively need <code>@RegisterForReflection</code>.</li><li>Classpath scanning at runtime does not exist, so libraries that rely on it need an extension or do not work.</li></ul>\n<h2>Dev mode replaces the restart loop</h2>\n<pre><code class=\"language-bash\">./mvnw quarkus:dev</code></pre>\n<p>Dev mode watches your sources, recompiles on the next request and keeps a continuous test runner you toggle with <code>r</code>. See <a href=\"/library/quarkus-dev-mode-use-continuous-testing\">Quarkus dev mode and continuous testing</a>. Dev Services start containers for databases and brokers when no URL is configured, which is what Testcontainers does for Spring tests, built in. The details are in <a href=\"/library/quarkus-dev-services-use-databases-brokers\">Quarkus Dev Services</a>.</p>\n<h2>Configuration and profiles</h2>\n<p><code>application.properties</code> works the way you expect, with profile prefixes written as <code>%dev.</code>, <code>%test.</code> and <code>%prod.</code>:</p>\n<pre data-filename=\"src/main/resources/application.properties\"><code class=\"language-properties\">quarkus.datasource.db-kind=postgresql\n%prod.quarkus.datasource.jdbc.url=jdbc:postgresql://db:5432/shop\n%dev.quarkus.hibernate-orm.database.generation=drop-and-create</code></pre>\n<p>An environment variable <code>QUARKUS_DATASOURCE_JDBC_URL</code> overrides the property at runtime, as long as the property is not build-time fixed.</p>\n<h2>Native images</h2>\n<p>A native build compiles your application ahead of time with GraalVM or Mandrel (<a href=\"https://quarkus.io/guides/building-native-image\">native image guide</a>):</p>\n<pre><code class=\"language-bash\">./mvnw package -Dnative</code></pre>\n<p>The result starts in milliseconds and has a small resident set, and the build takes minutes and a lot of memory. Everything reflective must be declared, so the typical failure is a class that exists in the jar and is missing from the image; <a href=\"/library/quarkus-native-build-failed-reflection-fix\">Quarkus native build failures with reflection</a> shows the fix. Use native for scale-to-zero functions and command-line tools. A long-running service that uses the JIT well often does not need it.</p>\n<h2>Measure before you move</h2>\n<p>The speed argument for Quarkus is true, and it is also the argument most teams do not need. A service that starts once a week and runs for days gets little from a faster start. The memory argument matters more for density: more instances per node. Measure your own service's startup time and resident memory on both frameworks before you commit, because the gap depends on how many libraries you load. <a href=\"/library/quarkus-starts-fast\">What Quarkus is and why it starts fast</a> explains the mechanics.</p>\n<h2>The data layer: Spring Data against Panache</h2>\n<p>Most of the code a Spring developer writes touches a repository, so this is where the mapping pays off first. A Spring Data repository is an interface the framework implements:</p>\n<pre><code class=\"language-java\">public interface OrderRepository extends JpaRepository&lt;Order, Long&gt; {\n    List&lt;Order&gt; findByStatusOrderByCreatedAtDesc(OrderStatus status);\n\n    @Query(\"select o from Order o where o.total &gt; :min\")\n    List&lt;Order&gt; bigOrders(@Param(\"min\") BigDecimal min);\n}</code></pre>\n<p>The Quarkus equivalent is Hibernate ORM with Panache, and it offers two styles. The repository style is the closest to what you know:</p>\n<pre><code class=\"language-java\">@ApplicationScoped\npublic class OrderRepository implements PanacheRepository&lt;Order&gt; {\n\n    public List&lt;Order&gt; byStatus(OrderStatus status) {\n        return list(\"status = ?1 order by createdAt desc\", status);\n    }\n\n    public List&lt;Order&gt; bigOrders(BigDecimal min) {\n        return list(\"total &gt; :min\", Parameters.with(\"min\", min));\n    }\n}</code></pre>\n<p>The active record style puts the queries on the entity itself, which is shorter and reads like Rails, and some teams dislike it for exactly that reason:</p>\n<pre><code class=\"language-java\">@Entity\npublic class Order extends PanacheEntity {\n\n    public OrderStatus status;\n    public BigDecimal total;\n    public Instant createdAt;\n\n    public static List&lt;Order&gt; byStatus(OrderStatus status) {\n        return list(\"status = ?1 order by createdAt desc\", status);\n    }\n}</code></pre>\n<p>Two differences matter in practice. Panache does not generate queries from method names, so <code>findByStatusOrderByCreatedAtDesc</code> has no equivalent and you write the short query yourself, which is more typing and also more explicit. And the entity in the active record style has public fields, which Quarkus rewrites to accessors at build time. If you want Spring's derived queries, the <code>quarkus-spring-data-jpa</code> compatibility extension supports a subset of them, and it is a good bridge while migrating, not a place to stay.</p>\n<p>Transactions use the Jakarta annotation, and the rule you know still applies: the boundary is the proxy, so a call from one method to another in the same bean does not start one.</p>\n<pre><code class=\"language-java\">@ApplicationScoped\npublic class OrderService {\n\n    @Inject OrderRepository orders;\n\n    @Transactional\n    public Order place(NewOrder request) {\n        Order order = new Order();\n        order.status = OrderStatus.PLACED;\n        order.total = request.total();\n        order.createdAt = Instant.now();\n        orders.persist(order);\n        return order;\n    }\n}</code></pre>\n<p>Use <code>jakarta.transaction.Transactional</code> here, not Spring's, and prefer <code>@Transactional(Transactional.TxType.SUPPORTS)</code> or no annotation on read paths. There is no <code>readOnly</code> flag, so the cheap way to avoid dirty checking on a read-heavy query is to select into a DTO with <code>project(OrderSummary.class)</code>.</p>\n<h2>Configuration: from <code>@ConfigurationProperties</code> to <code>@ConfigMapping</code></h2>\n<p>A typed configuration group in Spring:</p>\n<pre><code class=\"language-java\">@ConfigurationProperties(prefix = \"shop\")\npublic record ShopProperties(String currency, Duration cacheTtl, Pricing pricing) {\n    public record Pricing(BigDecimal taxRate) {}\n}</code></pre>\n<p>In Quarkus it is an interface, with defaults on the methods:</p>\n<pre><code class=\"language-java\">@ConfigMapping(prefix = \"shop\")\npublic interface ShopConfig {\n\n    @WithDefault(\"EUR\")\n    String currency();\n\n    @WithName(\"cache-ttl\")\n    @WithDefault(\"5m\")\n    Duration cacheTtl();\n\n    Pricing pricing();\n\n    interface Pricing {\n        @WithDefault(\"0.20\")\n        BigDecimal taxRate();\n    }\n}</code></pre>\n<pre><code class=\"language-properties\">shop.currency=USD\nshop.pricing.tax-rate=0.08</code></pre>\n<p>Inject it like any bean with <code>@Inject ShopConfig config</code>. For a single value, <code>@ConfigProperty(name = \"shop.currency\", defaultValue = \"EUR\") String currency</code> is the <code>@Value</code> equivalent. The part that surprises Spring developers is validation at startup: a mapping with a missing required value fails the application at boot with a message naming the property, which is the behavior you wanted from <code>@Validated</code> configuration, free of charge.</p>\n<h2>Calling other services: <code>RestClient</code> against the REST Client</h2>\n<p>Spring's <code>RestClient</code> is imperative and built in code. Quarkus uses a declarative interface, in the style of Feign or Spring's HTTP interface clients:</p>\n<pre><code class=\"language-java\">@RegisterRestClient(configKey = \"pricing\")\n@Path(\"/prices\")\npublic interface PricingClient {\n\n    @GET\n    @Path(\"/{sku}\")\n    @Produces(MediaType.APPLICATION_JSON)\n    Price priceOf(@PathParam(\"sku\") String sku);\n}</code></pre>\n<pre><code class=\"language-properties\">quarkus.rest-client.pricing.url=http://pricing:8080\nquarkus.rest-client.pricing.connect-timeout=300\nquarkus.rest-client.pricing.read-timeout=1000</code></pre>\n<p>Inject it with <code>@Inject @RestClient PricingClient pricing</code>. Resilience comes from the SmallRye Fault Tolerance extension, which implements the MicroProfile annotations and replaces Resilience4j in most Spring services:</p>\n<pre><code class=\"language-java\">@ApplicationScoped\npublic class CatalogService {\n\n    @Inject @RestClient PricingClient pricing;\n\n    @Retry(maxRetries = 2, delay = 200, jitter = 100)\n    @Timeout(1500)\n    @CircuitBreaker(requestVolumeThreshold = 20, failureRatio = 0.5, delay = 10_000)\n    @Fallback(fallbackMethod = \"unknownPrice\")\n    public Price price(String sku) {\n        return pricing.priceOf(sku);\n    }\n\n    Price unknownPrice(String sku) {\n        return Price.unknown(sku);\n    }\n}</code></pre>\n<p>The same advice holds as anywhere: retry only reads, and make the fallback honest.</p>\n<h2>Error handling: <code>@ControllerAdvice</code> becomes an exception mapper</h2>\n<p>A Spring Boot <code>@RestControllerAdvice</code> has two Quarkus counterparts. For a handful of exceptions, annotate a method in any class with <code>@ServerExceptionMapper</code>:</p>\n<pre><code class=\"language-java\">public class ApiErrors {\n\n    @ServerExceptionMapper\n    public RestResponse&lt;ProblemBody&gt; notFound(OrderNotFound e) {\n        return RestResponse.status(Response.Status.NOT_FOUND,\n            new ProblemBody(\"order-not-found\", e.getMessage()));\n    }\n\n    @ServerExceptionMapper\n    public RestResponse&lt;ProblemBody&gt; invalid(ConstraintViolationException e) {\n        return RestResponse.status(Response.Status.BAD_REQUEST,\n            new ProblemBody(\"validation-failed\", e.getMessage()));\n    }\n}</code></pre>\n<p>The portable form is a class that implements <code>ExceptionMapper&lt;T&gt;</code> and carries <code>@Provider</code>, which works in any JAX-RS runtime. Bean Validation is the same Hibernate Validator you know, so <code>@Valid</code> on a parameter and constraints on a record behave identically, and a violation reaches the mapper as the exception above.</p>\n<h2>Security in one table</h2>\n<table><thead><tr><th>Spring Security</th><th>Quarkus</th></tr></thead><tbody><tr><td><code>SecurityFilterChain</code> with <code>authorizeHttpRequests</code></td><td><code>quarkus.http.auth.permission.*</code> properties, or annotations</td></tr><tr><td><code>@PreAuthorize(\"hasRole('ADMIN')\")</code></td><td><code>@RolesAllowed(\"ADMIN\")</code></td></tr><tr><td><code>oauth2ResourceServer().jwt()</code></td><td><code>quarkus-smallrye-jwt</code> or <code>quarkus-oidc</code></td></tr><tr><td>Keycloak adapter or OAuth2 client</td><td><code>quarkus-oidc</code> with Dev Services for Keycloak</td></tr></tbody></table>\n<pre><code class=\"language-properties\">quarkus.http.auth.permission.admin.paths=/admin/*\nquarkus.http.auth.permission.admin.policy=authenticated\nmp.jwt.verify.publickey.location=publicKey.pem\nmp.jwt.verify.issuer=https://auth.example.com</code></pre>\n<pre><code class=\"language-java\">@Path(\"/orders\")\n@RolesAllowed(\"customer\")\npublic class OrderResource {\n\n    @Inject JsonWebToken jwt;\n\n    @GET\n    public List&lt;OrderView&gt; mine() {\n        return service.forCustomer(jwt.getSubject());\n    }\n}</code></pre>\n<p>Quarkus secures by path or by annotation, and denies by default only if you set a deny policy, so state it explicitly with <code>quarkus.security.jaxrs.deny-unannotated-endpoints=true</code> for an API where every endpoint should carry a role.</p>\n<h2>Scheduling, startup and events</h2>\n<p>The small framework features have direct mappings, and they are where a migrating team trips over a missing dependency, not over a concept:</p>\n<pre><code class=\"language-java\">@ApplicationScoped\npublic class Jobs {\n\n    @Scheduled(every = \"10m\", concurrentExecution = Scheduled.ConcurrentExecution.SKIP)\n    void refreshPrices() {\n        // like @Scheduled(fixedRate = ...) in Spring\n    }\n\n    void onStart(@Observes StartupEvent event) {\n        // like an ApplicationRunner or @EventListener(ApplicationReadyEvent.class)\n    }\n\n    void onOrderPlaced(@Observes OrderPlaced event) {\n        // like @EventListener, with CDI events fired from Event&lt;OrderPlaced&gt;.fire(...)\n    }\n}</code></pre>\n<p>Add the <code>quarkus-scheduler</code> extension for <code>@Scheduled</code>, since nothing is on the classpath you did not ask for, which is the same build-time principle in another form. Producer methods with <code>@Produces</code> replace <code>@Bean</code> methods, qualifiers replace <code>@Qualifier</code>, and <code>@IfBuildProfile(\"dev\")</code> or <code>@LookupIfProperty</code> replace <code>@Profile</code> and <code>@ConditionalOnProperty</code>. The profile conditions are decided at build time, which is the one place the model really differs: a bean excluded for <code>prod</code> is not present in the artifact at all.</p>\n<h2>Testing: <code>@QuarkusTest</code> and Dev Services</h2>\n<p>A Spring Boot web test and its Quarkus counterpart look alike, with RestAssured as the usual client:</p>\n<pre><code class=\"language-java\">@QuarkusTest\nclass OrderResourceTest {\n\n    @InjectMock\n    PricingClient pricing;\n\n    @Test\n    void createsAnOrder() {\n        Mockito.when(pricing.priceOf(\"sku-1\")).thenReturn(new Price(\"sku-1\", new BigDecimal(\"19.90\")));\n\n        given()\n            .contentType(ContentType.JSON)\n            .body(\"\"\"\n                {\"sku\":\"sku-1\",\"quantity\":2}\"\"\")\n        .when()\n            .post(\"/orders\")\n        .then()\n            .statusCode(201)\n            .header(\"Location\", containsString(\"/orders/\"))\n            .body(\"total\", is(39.80f));\n    }\n}</code></pre>\n<p><code>@InjectMock</code> replaces <code>@MockitoBean</code>, and the database comes from Dev Services without a line of container code when no JDBC URL is set for the <code>test</code> profile. <code>@QuarkusIntegrationTest</code> runs the same tests against the packaged artifact or the native binary, which is how you catch a reflection gap before production. A <code>@QuarkusTest</code> application starts once and is shared across test classes with the same profile, like the Spring context cache, and <code>@TestProfile</code> creates a separate one when a test needs different configuration.</p>\n<h2>Containers and operations</h2>\n<p>A JVM-mode image follows the same layered idea as a Spring Boot image. Quarkus generates Dockerfiles under <code>src/main/docker</code>:</p>\n<pre><code class=\"language-dockerfile\">FROM registry.access.redhat.com/ubi9/openjdk-21-runtime:latest\nCOPY --chown=185 target/quarkus-app/lib/ /deployments/lib/\nCOPY --chown=185 target/quarkus-app/*.jar /deployments/\nCOPY --chown=185 target/quarkus-app/app/ /deployments/app/\nCOPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/\nUSER 185\nENTRYPOINT [\"java\", \"-jar\", \"/deployments/quarkus-run.jar\"]</code></pre>\n<p>Use the Dockerfile that <code>quarkus create</code> generated for the Java version you target, and check which base image matches your JDK, since the tag above is an illustration. The <code>quarkus-smallrye-health</code> extension gives <code>/q/health/live</code> and <code>/q/health/ready</code>, and the Micrometer extension serves <code>/q/metrics</code>, so Kubernetes probes and Prometheus scrapes need only the new paths. Management endpoints sit under <code>/q</code> by default, which is worth remembering when a Spring-trained eye looks for <code>/actuator</code>.</p>\n<h2>A migration order that works</h2>\n<p>Teams that move a service rather than start fresh succeed with a sequence like this:</p>\n<ol><li>Create the Quarkus project with the extensions that match the Spring starters (REST, Hibernate ORM with Panache, the same JDBC driver, Validator, OIDC or JWT).</li><li>Move the domain and the pure logic over unchanged. Plain classes need no change at all.</li><li>Rewrite the edges: resources for controllers, repositories for Spring Data, <code>@ConfigMapping</code> for properties.</li><li>Port the tests, and run them in dev mode with continuous testing on.</li><li>Build the native image only if you need it, and run the integration tests against it in CI.</li><li>Compare startup time, resident memory and throughput with the original under the same load before you decide the move was worth it.</li></ol>\n<p>For services with heavy Spring dependencies, the <code>quarkus-spring-di</code>, <code>quarkus-spring-web</code> and <code>quarkus-spring-data-jpa</code> extensions let you keep many annotations while you migrate, and they are best treated as scaffolding that you remove once the service is stable, since the idiomatic Quarkus forms are what the documentation and the community use.</p>\n<h2>Mistakes Spring developers make in the first month</h2>\n<table><thead><tr><th>Mistake</th><th>What happens</th><th>Fix</th></tr></thead><tbody><tr><td>Changing a build-time property through an environment variable</td><td>No effect on the deployed jar</td><td>Rebuild, or check the configuration reference for the property's phase</td></tr><tr><td>Assuming a bean is created by component scanning</td><td>Bean missing, or a build error about an unsatisfied dependency</td><td>Add a bean-defining annotation such as <code>@ApplicationScoped</code></td></tr><tr><td>Using reflection on your own classes in a native image</td><td>Works on the JVM, fails natively</td><td><code>@RegisterReflectionForBinding</code> or <code>@RegisterForReflection</code></td></tr><tr><td>Expecting <code>readOnly</code> transactions</td><td>No such attribute</td><td>Project into DTOs for reads</td></tr><tr><td>Reaching for <code>@Autowired</code> on a private field</td><td>Compiles with the compatibility extension, surprises in review</td><td>Use <code>@Inject</code> and package-private fields or constructors</td></tr><tr><td>Looking for <code>/actuator/health</code></td><td>404</td><td>Use <code>/q/health</code></td></tr></tbody></table>\n<h2>Threads: the event loop is the new thing to learn</h2>\n<p>Spring MVC gives every request a thread from a pool, and blocking is normal. Quarkus REST runs on an event loop by default for methods that return a reactive type, and on a worker thread for methods that return plain objects. The rule that follows is simple and easy to break: never block an I/O thread. A resource that returns <code>Uni&lt;Order&gt;</code> and calls a blocking JDBC method inside it will freeze the event loop, and the log says so:</p>\n<pre><code class=\"language-text\">WARN  [io.qua.ver.cor.run.VertxCoreRecorder] Thread Thread[vert.x-eventloop-thread-1,5,main] has been blocked for 2610 ms</code></pre>\n<p>For a Spring developer arriving from Spring MVC, the least surprising approach is to write blocking code in plain methods that return objects, and let Quarkus run them on worker threads. If you want the thread-per-request simplicity with the scalability of virtual threads, annotate the endpoint:</p>\n<pre><code class=\"language-java\">@Path(\"/orders\")\npublic class OrderResource {\n\n    @Inject OrderService orders;\n\n    @GET\n    @Path(\"/{id}\")\n    @RunOnVirtualThread\n    public OrderView get(@PathParam(\"id\") long id) {\n        return orders.view(id);        // blocking JDBC is fine here\n    }\n}</code></pre>\n<p><code>@RunOnVirtualThread</code> needs a JDK with virtual threads, which every current LTS release has, and it is the closest equivalent to setting <code>spring.threads.virtual.enabled=true</code> in Spring Boot. The caveat is the same on both sides: a <code>synchronized</code> block that holds a monitor across blocking I/O can pin a carrier thread in older JDK releases, so check your libraries before you switch a busy service.</p>\n<h2>Caching and OpenAPI, the two extensions you will add first</h2>\n<p>Spring's <code>@Cacheable</code> becomes <code>@CacheResult</code> from the <code>quarkus-cache</code> extension. The shape is identical, and the cache itself is configured by name:</p>\n<pre><code class=\"language-java\">@ApplicationScoped\npublic class PriceService {\n\n    @CacheResult(cacheName = \"prices\")\n    public Price priceOf(@CacheKey String sku) {\n        return pricing.priceOf(sku);\n    }\n\n    @CacheInvalidate(cacheName = \"prices\")\n    public void priceChanged(@CacheKey String sku) {\n    }\n}</code></pre>\n<pre><code class=\"language-properties\">quarkus.cache.caffeine.\"prices\".expire-after-write=10M\nquarkus.cache.caffeine.\"prices\".maximum-size=5000</code></pre>\n<p>The self-invocation rule applies, since these are interceptors on a proxied bean. For API documentation, add <code>quarkus-smallrye-openapi</code> and the specification is served at <code>/q/openapi</code>, with Swagger UI at <code>/q/swagger-ui</code> in dev mode. Nothing needs configuring until you want to describe an endpoint more precisely with <code>@Operation</code> or <code>@APIResponse</code>, which come from the MicroProfile OpenAPI annotations and play the role of Springdoc's.</p>\n<h2>Measure the two frameworks on your own service</h2>\n<p>The performance claims are the reason many teams look at Quarkus, so test them on the service you would migrate, and on equal terms. Start both from a clean container, wait for readiness and record the numbers that matter for your deployment:</p>\n<pre><code class=\"language-bash\">docker run -d --name spring-shop --memory 512m -p 8081:8080 shop-spring:1.0\ndocker run -d --name quarkus-shop --memory 512m -p 8082:8080 shop-quarkus:1.0\n\nfor name in spring-shop quarkus-shop; do\n  echo \"== $name\"\n  docker logs $name 2&gt;&amp;1 | grep -iE \"started .* in|started in|Quarkus .* started in\"\n  docker stats --no-stream --format \"memory: {{.MemUsage}}\" $name\ndone</code></pre>\n<p>Then put both under the same load with a tool such as <code>wrk</code> or <code>hey</code> for a few minutes, and read the resident memory again after the run, since the first figure is idle memory and the second is what you will pay for at traffic. Repeat the experiment three times and report the median. The result differs for each service, because it depends on the libraries the service loads. A thin REST service can show a large gap, and a service dominated by a heavy dependency can show a small one. Make the decision from the table you produce, and keep the table in the pull request that proposes the migration.</p>\n<h2>A short checklist before you commit</h2>\n<p>Ask five questions of the service you have in mind. Does it use libraries without a Quarkus extension, and if so do they work on the classpath in JVM mode? Does it rely on runtime conditionals, such as beans created from a property value read at startup, which becomes build-time configuration? Does the team have a place to run native builds, with the memory and time they need? Are the people who will be on call comfortable with a new set of management endpoints and log formats? And does the measured gain matter to the business, in dollars of infrastructure or in seconds of cold start? Four yeses make a good migration, and fewer mean the new framework is a hobby for the team and not an improvement for the service.</p>\n<h2>When to stay on Spring</h2>\n<p>Stay on Spring when your team knows it, when your libraries are Spring-first (Spring Security, Spring Cloud, Spring Batch) or when you rely on runtime flexibility such as conditional beans decided from properties at startup. Move to Quarkus when density, cold start or a container budget is the constraint. Mixed estates exist, and a Quarkus service next to Spring services is fine because both speak HTTP and JDBC.</p>","date_published":"2026-11-14T04:22:31+00:00","tags":["Quarkus"]},{"id":"https://javahacks.dev/library/junit-5-handbook","url":"https://javahacks.dev/library/junit-5-handbook","title":"The JUnit 5 Handbook for Readable Fast Reliable Tests","summary":"A working reference to JUnit 5 and the JUnit 6 line: lifecycle, assertions, parameterized tests, extensions and the habits that keep suites fast.","content_html":"<p>A test suite is read far more often than it is written, and most unreadable suites share one cause: tests that repeat their setup, assert three unrelated things and fail with a message that says only <code>expected: &lt;true&gt; but was: &lt;false&gt;</code>. JUnit 5 has the tools to prevent all of that, and most projects use about a fifth of them. This handbook covers the parts you will use daily, with the versions pinned in the prose. The code uses JUnit Jupiter 5.13 on JDK 25. JUnit 6 keeps the same <code>org.junit.jupiter.api</code> package, requires Java 17 or newer and unifies the version of its three parts.</p>\n<p>The <a href=\"https://junit.org/junit5/docs/current/user-guide/\">JUnit user guide</a> is the primary reference. For the wider question of what to test at all, read <a href=\"/library/java-testing-strategy-practical\">a practical Java testing strategy</a>. This page is about the framework.</p>\n<h2>Three projects under one name</h2>\n<p>JUnit 5 is the Platform (launching tests and the engine API that IDEs and build tools call), Jupiter (the annotations and assertions you write) and Vintage (an engine for JUnit 3 and 4). The split is why a build can run old and new tests side by side. <a href=\"/library/junit-5-architecture-platform-jupiter-vintage\">JUnit 5 architecture</a> explains how they fit together, and it is where to look when a build tool reports that no tests were found.</p>\n<h2>A first test, and why the class is package-private</h2>\n<pre data-filename=\"src/test/java/dev/javahacks/MoneyTest.java\"><code class=\"language-java\">import static org.junit.jupiter.api.Assertions.*;\n\nimport org.junit.jupiter.api.DisplayName;\nimport org.junit.jupiter.api.Test;\n\nclass MoneyTest {\n\n    @Test\n    @DisplayName(\"adding two amounts in the same currency sums the cents\")\n    void addsSameCurrency() {\n        var total = new Money(250, \"USD\").plus(new Money(150, \"USD\"));\n\n        assertEquals(400, total.cents());\n    }\n}</code></pre>\n<p>Jupiter does not require <code>public</code> classes or methods. Package-private keeps tests quiet in the IDE's auto-complete and costs nothing. The expected value goes first in <code>assertEquals</code>; reversing the arguments produces a message that blames the wrong side. Setup for a first project, in both Maven and Gradle, is in the <a href=\"/library/junit-5-tutorial-beginners-maven-gradle\">JUnit 5 tutorial for beginners</a>.</p>\n<h2>Lifecycle: a new instance per method</h2>\n<p>By default JUnit creates a new instance of the test class for every test method. That is why instance fields do not leak between tests, and why <code>@BeforeAll</code> methods must be <code>static</code>. The order is <code>@BeforeAll</code>, then for each test <code>@BeforeEach</code>, the test, <code>@AfterEach</code>, and finally <code>@AfterAll</code>.</p>\n<pre><code class=\"language-java\">@TestInstance(TestInstance.Lifecycle.PER_CLASS)\nclass ExpensiveFixtureTest {\n    // one instance for all methods; @BeforeAll no longer has to be static\n}</code></pre>\n<p>Switch to <code>PER_CLASS</code> only when a fixture is costly to build and read-only afterwards. It trades isolation for speed, and the trade is yours to make. Test method order is deterministic but intentionally not obvious, so never depend on it. <a href=\"/library/junit-5-lifecycle-annotations-execution-order\">Lifecycle annotations and execution order</a> lists every callback.</p>\n<h2>Assertions that explain themselves</h2>\n<p>Prefer the assertion that names what you mean. <code>assertEquals</code>, <code>assertTrue</code>, <code>assertNull</code>, <code>assertIterableEquals</code> and <code>assertThrows</code> all produce better failures than <code>assertTrue(a.equals(b))</code>. Two deserve attention:</p>\n<pre><code class=\"language-java\">@Test\nvoid rejectsNegativeAmounts() {\n    var error = assertThrows(IllegalArgumentException.class, () -&gt; new Money(-1, \"USD\"));\n\n    assertEquals(\"cents must not be negative: -1\", error.getMessage());\n}\n\n@Test\nvoid exposesAllFields() {\n    var money = new Money(250, \"usd\");\n\n    assertAll(\"money\",\n        () -&gt; assertEquals(250, money.cents()),\n        () -&gt; assertEquals(\"USD\", money.currency()));\n}</code></pre>\n<p><code>assertThrows</code> returns the exception so you can assert on its message. <code>assertAll</code> runs every lambda and reports all failures, which is the difference between fixing a test in one run and fixing it in three. More on both in <a href=\"/library/junit-assertthrows-assertall-use-properly\">assertThrows and assertAll</a> and <a href=\"/library/junit-5-assertions-write-readable\">readable assertions</a>. If you prefer fluent assertions, AssertJ works alongside JUnit with no integration code.</p>\n<h2>Parameterized tests replace copy and paste</h2>\n<pre><code class=\"language-java\">@ParameterizedTest(name = \"{0} cents in {1} formats as {2}\")\n@CsvSource({\n    \"100, USD, $1.00\",\n    \"5,   USD, $0.05\",\n    \"1999, EUR, 19.99 EUR\"\n})\nvoid formatsMoney(long cents, String currency, String expected) {\n    assertEquals(expected, new Money(cents, currency).format());\n}</code></pre>\n<p>Each row appears as its own test with the name you give it. Use <code>@MethodSource</code> when the arguments are objects, and <code>@EnumSource</code> to cover every constant of an enum. Add the <code>junit-jupiter-params</code> dependency; the <code>junit-jupiter</code> aggregate artifact includes it.</p>\n<h2>Structure with nested classes</h2>\n<p><code>@Nested</code> groups tests by the situation they describe, and each nested class can have its own <code>@BeforeEach</code>:</p>\n<pre><code class=\"language-java\">class ShoppingCartTest {\n\n    @Nested\n    class WhenEmpty {\n        @Test\n        void totalIsZero() { /* ... */ }\n    }\n\n    @Nested\n    class WithItems {\n        @BeforeEach\n        void addItems() { /* ... */ }\n    }\n}</code></pre>\n<p>Nested classes read well in IDE output and Maven reports because the hierarchy becomes the test's name.</p>\n<h2>Extensions replace runners and rules</h2>\n<p>An extension hooks into the lifecycle. Register one with <code>@ExtendWith</code>, and combine as many as you need. Frameworks ship their own (<code>MockitoExtension</code>, <code>SpringExtension</code>), and built-in ones cover common needs such as <code>@TempDir</code> for a temporary directory:</p>\n<pre><code class=\"language-java\">@Test\nvoid writesReport(@TempDir Path dir) throws IOException {\n    Path report = dir.resolve(\"report.txt\");\n    Files.writeString(report, \"ok\");\n    assertEquals(\"ok\", Files.readString(report));\n}</code></pre>\n<p>JUnit deletes the directory when the test ends. For Mockito, <code>@ExtendWith(MockitoExtension.class)</code> enables strict stubs, which is the source of [<code>UnnecessaryStubbingException</code>](/library/unnecessarystubbingexception-fix-mockito-junit-5) when a stub goes unused.</p>\n<h2>Speed and parallel runs</h2>\n<p>Create <code>src/test/resources/junit-platform.properties</code>:</p>\n<pre><code class=\"language-properties\">junit.jupiter.execution.parallel.enabled=true\njunit.jupiter.execution.parallel.mode.default=same_thread\njunit.jupiter.execution.parallel.mode.classes.default=concurrent</code></pre>\n<p>This runs test classes in parallel while keeping the methods in each class sequential, which is the safest first step. A suite that breaks under parallelism has shared state, usually a static field, a shared file or a fixed port. Fix that rather than turning parallelism off.</p>\n<h2>When tests do not run</h2>\n<p>A green build with zero tests executed is a configuration problem, and it usually means the Surefire version predates JUnit Platform support or the wrong engine is on the classpath. <a href=\"/library/junit-5-tests-not-running-maven\">JUnit 5 tests not running in Maven Surefire</a> lists the causes, and <a href=\"/library/junit-no-runnable-methods-fix-initialization\">no runnable methods</a> covers the JUnit 4 message that appears when a class mixes the two APIs.</p>\n<h2>Set up the build once, correctly</h2>\n<p>Most \"JUnit does not work\" reports are build configuration. Import the bill of materials so that the Platform, Jupiter and the launcher stay on matching versions, and keep one version number to update:</p>\n<pre><code class=\"language-xml\">&lt;dependencyManagement&gt;\n  &lt;dependencies&gt;\n    &lt;dependency&gt;\n      &lt;groupId&gt;org.junit&lt;/groupId&gt;\n      &lt;artifactId&gt;junit-bom&lt;/artifactId&gt;\n      &lt;version&gt;5.11.4&lt;/version&gt;\n      &lt;type&gt;pom&lt;/type&gt;\n      &lt;scope&gt;import&lt;/scope&gt;\n    &lt;/dependency&gt;\n  &lt;/dependencies&gt;\n&lt;/dependencyManagement&gt;\n\n&lt;dependencies&gt;\n  &lt;dependency&gt;\n    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;\n    &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;\n    &lt;scope&gt;test&lt;/scope&gt;\n  &lt;/dependency&gt;\n  &lt;dependency&gt;\n    &lt;groupId&gt;org.assertj&lt;/groupId&gt;\n    &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;\n    &lt;version&gt;3.27.3&lt;/version&gt;\n    &lt;scope&gt;test&lt;/scope&gt;\n  &lt;/dependency&gt;\n&lt;/dependencies&gt;</code></pre>\n<p>The version numbers above are examples that were current when this page was written, so check the project's release page for the one to use. With Gradle the equivalent is short, and one line is easy to forget on recent Gradle versions:</p>\n<pre><code class=\"language-kotlin\">dependencies {\n    testImplementation(platform(\"org.junit:junit-bom:5.11.4\"))\n    testImplementation(\"org.junit.jupiter:junit-jupiter\")\n    testRuntimeOnly(\"org.junit.platform:junit-platform-launcher\")\n}\n\ntasks.test {\n    useJUnitPlatform()\n}</code></pre>\n<p><code>useJUnitPlatform()</code> is what makes Gradle run Jupiter tests, and without it the build is green with zero tests. On Maven, Surefire 3.0.0 or later is needed for the Platform, and an older version is the usual reason a project reports \"No tests to run\".</p>\n<h2>The lifecycle, observed</h2>\n<p>Reading about callback order is less convincing than watching it. This class prints each hook, and running it once teaches the sequence:</p>\n<pre><code class=\"language-java\">class LifecycleTest {\n\n    @BeforeAll static void beforeAll() { System.out.println(\"beforeAll\"); }\n    @AfterAll  static void afterAll()  { System.out.println(\"afterAll\"); }\n\n    LifecycleTest() { System.out.println(\"  constructor\"); }\n\n    @BeforeEach void beforeEach() { System.out.println(\"  beforeEach\"); }\n    @AfterEach  void afterEach()  { System.out.println(\"  afterEach\"); }\n\n    @Test void first()  { System.out.println(\"    test first\"); }\n    @Test void second() { System.out.println(\"    test second\"); }\n}</code></pre>\n<pre><code class=\"language-text\">beforeAll\n  constructor\n  beforeEach\n    test first\n  afterEach\n  constructor\n  beforeEach\n    test second\n  afterEach\nafterAll</code></pre>\n<p>Notice two constructor lines: one instance per test method. The order of <code>first</code> and <code>second</code> can vary, which is by design. Put expensive work in <code>@BeforeAll</code> only when it is read-only afterwards, and put cleanup in <code>@AfterEach</code> so that a failing test still cleans up, because the <code>@AfterEach</code> and <code>@AfterAll</code> methods run even when the test throws.</p>\n<h2>More assertions, and when a test should not run</h2>\n<p>Beyond equality, a few assertions pay for themselves. <code>assertInstanceOf</code> checks a type and returns the cast value, which removes a cast and a failure mode:</p>\n<pre><code class=\"language-java\">@Test\nvoid parsesAnIntegerLiteral() {\n    Node node = parser.parse(\"42\");\n\n    IntLiteral literal = assertInstanceOf(IntLiteral.class, node);\n    assertEquals(42, literal.value());\n}</code></pre>\n<p><code>assertTimeout</code> fails a test that runs too long, and it runs the code in the calling thread, so it reports the overrun after the code finishes. <code>assertTimeoutPreemptively</code> interrupts it on another thread, which breaks anything that depends on thread-local state, such as a Spring transaction opened by the test. Use the annotation form for a whole test:</p>\n<pre><code class=\"language-java\">@Test\n@Timeout(value = 2, unit = TimeUnit.SECONDS)\nvoid importsTheSampleFileQuickly() {\n    importer.run(Path.of(\"src/test/resources/sample.csv\"));\n}</code></pre>\n<p>Assumptions abort a test as skipped, not failed, when a precondition does not hold. Use them for the environment, never to hide a failure:</p>\n<pre><code class=\"language-java\">@Test\nvoid readsFromTheSocket() {\n    assumeTrue(System.getenv(\"CI\") == null, \"needs a local network\");\n    // ...\n}</code></pre>\n<p>Annotations do the same for common conditions, and they show up in the report as skipped with their reason:</p>\n<pre><code class=\"language-java\">@Test @EnabledOnOs(OS.LINUX)\nvoid usesProcFilesystem() { /* ... */ }\n\n@Test @EnabledIfEnvironmentVariable(named = \"DB_URL\", matches = \".+\")\nvoid talksToTheConfiguredDatabase() { /* ... */ }\n\n@Test @EnabledForJreRange(min = JRE.JAVA_21)\nvoid usesVirtualThreads() { /* ... */ }\n\n@Test @Disabled(\"flaky since the move to the new queue, tracked in SHOP-412\")\nvoid deliversInOrder() { /* ... */ }</code></pre>\n<p>A <code>@Disabled</code> without a reason and an issue number is a deletion in slow motion. Make the reason mandatory in review.</p>\n<h2>Parameterized tests beyond the basics</h2>\n<p>The earlier example used a CSV string. Real suites need more sources. <code>@MethodSource</code> provides objects, with names for the report:</p>\n<pre><code class=\"language-java\">static Stream&lt;Arguments&gt; discounts() {\n    return Stream.of(\n        Arguments.of(\"standard, small order\", new Order(Tier.STANDARD, 1), new BigDecimal(\"0.00\")),\n        Arguments.of(\"standard, bulk order\", new Order(Tier.STANDARD, 10), new BigDecimal(\"0.10\")),\n        Arguments.of(\"gold, bulk order\", new Order(Tier.GOLD, 10), new BigDecimal(\"0.15\")));\n}\n\n@ParameterizedTest(name = \"{0}\")\n@MethodSource(\"discounts\")\nvoid computesDiscount(String label, Order order, BigDecimal expected) {\n    assertEquals(0, expected.compareTo(policy.discountFor(order)));\n}</code></pre>\n<p>For a large table, keep it in a file next to the tests, where a product owner can review it without reading Java:</p>\n<pre><code class=\"language-java\">@ParameterizedTest\n@CsvFileSource(resources = \"/tax-rates.csv\", numLinesToSkip = 1)\nvoid appliesTaxRate(String country, String category, BigDecimal rate) {\n    assertEquals(0, rate.compareTo(taxes.rateFor(country, category)));\n}</code></pre>\n<p><code>@EnumSource</code> covers every constant and can exclude some, which turns \"every status has a label\" into one test:</p>\n<pre><code class=\"language-java\">@ParameterizedTest\n@EnumSource(value = OrderStatus.class, mode = EnumSource.Mode.EXCLUDE, names = \"UNKNOWN\")\nvoid everyStatusHasADisplayLabel(OrderStatus status) {\n    assertFalse(labels.labelFor(status).isBlank());\n}</code></pre>\n<p>When a test reads a value in a format JUnit cannot convert, write a converter once and apply it with <code>@ConvertWith</code>, instead of parsing strings at the top of every test. The tradeoff to remember is that a parameterized test hides one test method behind many runs, so keep the logic in the body trivial. If the body needs an <code>if</code> per case, the cases are different tests.</p>\n<h2>Tests that are generated, repeated or ordered</h2>\n<p><code>@RepeatedTest</code> runs a test several times, which is useful for a flaky-by-nature concurrency check. <code>@TestFactory</code> builds tests at runtime from data, and each dynamic test is reported separately:</p>\n<pre><code class=\"language-java\">@TestFactory\nStream&lt;DynamicTest&gt; everyFixtureFileParses() throws IOException {\n    try (Stream&lt;Path&gt; files = Files.list(Path.of(\"src/test/resources/fixtures\"))) {\n        return files.sorted()\n            .map(file -&gt; DynamicTest.dynamicTest(file.getFileName().toString(),\n                () -&gt; assertDoesNotThrow(() -&gt; parser.parse(Files.readString(file)))))\n            .toList().stream();\n    }\n}</code></pre>\n<p>Adding a fixture file adds a test with no code change. Ordering is the feature to use with the most care. Tests should not depend on each other, and the exception is a scripted scenario against real infrastructure, where steps share state by design:</p>\n<pre><code class=\"language-java\">@TestMethodOrder(MethodOrderer.OrderAnnotation.class)\nclass OrderLifecycleIT {\n\n    @Test @Order(1) void createsAnOrder()   { /* ... */ }\n    @Test @Order(2) void paysTheOrder()     { /* ... */ }\n    @Test @Order(3) void shipsTheOrder()    { /* ... */ }\n}</code></pre>\n<p>If you find yourself reaching for <code>@Order</code> in a unit test, the test is hiding a missing fixture. Use it for end-to-end flows, and label the class so that nobody copies the pattern.</p>\n<h2>Readable names without writing them twice</h2>\n<p>A <code>@DisplayName</code> on every method is accurate and tedious. Generate names from method names instead, and keep descriptive method names:</p>\n<pre><code class=\"language-java\">@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)\nclass MoneyTest {\n\n    @Test\n    void adding_amounts_in_different_currencies_is_rejected() {\n        assertThrows(CurrencyMismatch.class, () -&gt; new Money(1, \"USD\").plus(new Money(1, \"EUR\")));\n    }\n}</code></pre>\n<p>The report shows \"adding amounts in different currencies is rejected\". Set a project-wide default in <code>junit-platform.properties</code> with <code>junit.jupiter.displayname.generator.default</code>, and reserve <code>@DisplayName</code> for the rare test that needs punctuation or an issue number in the title.</p>\n<h2>Write your own extension</h2>\n<p>An extension is a class implementing callback interfaces, and writing one is the right answer when three test classes share setup that is not just a method. This extension measures each test and prints the slow ones, and shows the store, the parameter resolver and the registration:</p>\n<pre><code class=\"language-java\">public class SlowTestExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {\n\n    private static final Namespace NS = Namespace.create(SlowTestExtension.class);\n    private static final long THRESHOLD_MS = 500;\n\n    @Override\n    public void beforeEach(ExtensionContext context) {\n        context.getStore(NS).put(\"start\", System.nanoTime());\n    }\n\n    @Override\n    public void afterEach(ExtensionContext context) {\n        long start = context.getStore(NS).remove(\"start\", long.class);\n        long ms = (System.nanoTime() - start) / 1_000_000;\n        if (ms &gt; THRESHOLD_MS) {\n            System.out.printf(\"SLOW %s took %d ms%n\", context.getDisplayName(), ms);\n        }\n    }\n\n    @Override\n    public boolean supportsParameter(ParameterContext p, ExtensionContext c) {\n        return p.getParameter().getType() == Clock.class;\n    }\n\n    @Override\n    public Object resolveParameter(ParameterContext p, ExtensionContext c) {\n        return Clock.fixed(Instant.parse(\"2026-03-14T10:00:00Z\"), ZoneOffset.UTC);\n    }\n}</code></pre>\n<pre><code class=\"language-java\">@ExtendWith(SlowTestExtension.class)\nclass PricingTest {\n\n    @Test\n    void usesTheClockItIsGiven(Clock clock) {\n        assertEquals(Instant.parse(\"2026-03-14T10:00:00Z\"), clock.instant());\n    }\n}</code></pre>\n<p>The second capability, injecting a <code>Clock</code> into a test method, replaces a base class with a protected field. For an extension that needs configuration, register it as a field with <code>@RegisterExtension</code>, which lets you pass constructor arguments. To apply an extension to every test in a project, list it in <code>META-INF/services/org.junit.jupiter.api.extension.Extension</code> and set <code>junit.jupiter.extensions.autodetection.enabled=true</code>, though explicit registration is easier to follow when something goes wrong.</p>\n<h2>Tags, filters and the stages of a build</h2>\n<p>Not every test belongs in every run. Tag the slow ones and select by tag in the build:</p>\n<pre><code class=\"language-java\">@Tag(\"integration\")\nclass OrderRepositoryIT { /* ... */ }</code></pre>\n<pre><code class=\"language-xml\">&lt;plugin&gt;\n  &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;\n  &lt;configuration&gt;\n    &lt;excludedGroups&gt;integration&lt;/excludedGroups&gt;\n  &lt;/configuration&gt;\n&lt;/plugin&gt;</code></pre>\n<pre><code class=\"language-bash\">./mvnw test                              # fast stage, integration excluded\n./mvnw verify -Dgroups=integration       # integration stage</code></pre>\n<p>With Gradle, <code>useJUnitPlatform { includeTags(\"integration\") }</code> in a second <code>Test</code> task does the same. A tag is cheaper than a naming convention because it can be combined (<code>@Tag(\"slow\") @Tag(\"db\")</code>) and it survives renames. The mechanics, and how to fold several annotations into one, are in <a href=\"/library/junit-tags-filter-use-tests-5\">JUnit tags and filters</a>.</p>\n<h2>Parallel execution that stays correct</h2>\n<p>The configuration shown earlier runs classes in parallel. Fine-grained control comes from annotations on the classes that need it, which is how a suite stays fast without becoming flaky:</p>\n<pre><code class=\"language-java\">@Execution(ExecutionMode.SAME_THREAD)\n@ResourceLock(value = \"system-properties\", mode = ResourceAccessMode.READ_WRITE)\nclass ConfigurationLoaderTest {\n\n    @Test\n    void readsFromSystemProperty() {\n        System.setProperty(\"app.mode\", \"test\");\n        // ...\n    }\n}</code></pre>\n<p><code>@ResourceLock</code> says that tests using the named resource must not run at the same time as others that write it, and JUnit schedules around it. Global state, such as system properties, the default locale and time zone, static singletons and files at fixed paths, is the cause of nearly every parallel failure. Run a suite a few times with parallelism on in CI before you trust it, and when one test fails only in parallel, look for the shared thing before adding a lock. The best fix is no shared state, and the lock is the fix for the state you cannot remove.</p>\n<h2>Mockito with JUnit 5</h2>\n<p>Mockito integrates through its own extension, and strict stubs are on by default, which is a feature. An unused stub means the test and the code disagree:</p>\n<pre><code class=\"language-java\">@ExtendWith(MockitoExtension.class)\nclass CheckoutServiceTest {\n\n    @Mock PaymentGateway gateway;\n    @Mock InventoryClient inventory;\n    @InjectMocks CheckoutService service;\n\n    @Test\n    void chargesOnceAndReservesStock() {\n        when(gateway.charge(any())).thenReturn(Receipt.ok(\"r-1\"));\n\n        Receipt receipt = service.checkout(aCart());\n\n        assertEquals(\"r-1\", receipt.reference());\n        verify(inventory).reserve(\"sku-1\", 2);\n    }\n}</code></pre>\n<p>Verify the interactions that are the point of the test, such as the stock reservation above, and not every call. A suite that verifies each collaborator call is a copy of the implementation, and breaks when someone improves it. The distinctions are in <a href=\"/library/mock-java-leave-real-tests\">what to mock and what to leave real</a>.</p>\n<h2>Moving from JUnit 4</h2>\n<p>Migration is mostly mechanical, and a table covers the vocabulary:</p>\n<table><thead><tr><th>JUnit 4</th><th>JUnit 5</th></tr></thead><tbody><tr><td><code>@Before</code>, <code>@After</code></td><td><code>@BeforeEach</code>, <code>@AfterEach</code></td></tr><tr><td><code>@BeforeClass</code>, <code>@AfterClass</code></td><td><code>@BeforeAll</code>, <code>@AfterAll</code></td></tr><tr><td><code>@Ignore</code></td><td><code>@Disabled</code></td></tr><tr><td><code>@Category</code></td><td><code>@Tag</code></td></tr><tr><td><code>@RunWith</code>, <code>@Rule</code>, <code>@ClassRule</code></td><td><code>@ExtendWith</code>, <code>@RegisterExtension</code></td></tr><tr><td><code>@Test(expected = ...)</code></td><td><code>assertThrows</code></td></tr><tr><td><code>@Test(timeout = ...)</code></td><td><code>@Timeout</code></td></tr><tr><td><code>org.junit.Assert</code></td><td><code>org.junit.jupiter.api.Assertions</code></td></tr></tbody></table>\n<p>Keep the Vintage engine on the classpath while old and new tests coexist, convert one package at a time, and remove Vintage when the last JUnit 4 import is gone. Run the whole suite after each package, because a <code>@Rule</code> with side effects, such as a temporary folder or an expected-exception rule, behaves differently from its extension equivalent. The JUnit 6 line keeps the programming model described here, with a newer Java baseline, so the habits carry over. Check its release notes for the exact requirements before you upgrade.</p>\n<h2>Failures and where to look</h2>\n<table><thead><tr><th>Symptom</th><th>Likely cause</th><th>First move</th></tr></thead><tbody><tr><td>Build is green, zero tests ran</td><td>Old Surefire, missing <code>useJUnitPlatform()</code> or only Vintage present</td><td>Check the plugin version and the engine on the classpath</td></tr><tr><td><code>@BeforeAll</code> method must be static</td><td>Default per-method lifecycle</td><td>Make it <code>static</code>, or use <code>PER_CLASS</code></td></tr><tr><td>Test passes alone, fails in the suite</td><td>Shared static state or leaked fixture</td><td>Reset in <code>@AfterEach</code>, or remove the sharing</td></tr><tr><td>Fails only in parallel</td><td>Global state</td><td>Find it, then <code>@ResourceLock</code> or <code>@Execution(SAME_THREAD)</code></td></tr><tr><td><code>UnnecessaryStubbingException</code></td><td>A stub nobody called</td><td>Delete the stub or fix the code path</td></tr><tr><td>Parameterized test shows one case</td><td>Name pattern collapsed or one argument</td><td>Add <code>name = \"{0}\"</code> and inspect the arguments</td></tr><tr><td>Tag filter selects nothing</td><td>Typo in the tag or wrong plugin parameter</td><td>Compare the tag string and run with <code>-X</code></td></tr></tbody></table>\n<p>Most suites become trustworthy through a handful of habits: independent tests, small fixtures, names that state the behavior, and a decision to fix or delete every test that fails for no reason. The framework supports all four, and the discipline is the part you provide.</p>\n<h2>How to review a test</h2>\n<p>A test is code that other people must maintain, and review is where its quality is set. Ask five questions of every test in a pull request. What behavior does it protect, and could it be stated in one sentence? If the production code were deleted, would this test fail, and with a message that says why? Does it depend on anything it does not create, such as a record in a shared database, a file in the home directory or the order of another test? Is the setup visible in the test, or hidden in a base class four levels up? And does it assert on a result, or on how the result was obtained?</p>\n<p>Tests that fail these questions share a few shapes, and naming them helps a team spot them early. The first is the test that cannot fail, usually because the assertion is inside a callback that never runs, or because it asserts that a mock returns what it was told to return. The second is the test that restates the code: it computes the expected value with the same formula as the production method, so a wrong formula passes. The third is the oversized test, with a dozen assertions across unrelated behavior, whose name is <code>testProcess</code> and whose failure tells nobody anything. The fourth is the test with time in it, which uses <code>Thread.sleep</code> or the system clock and passes on a fast machine. The fifth is the test that needs a particular machine: a hard-coded path, a locale, a time zone or a port. Each of them has a plain remedy in the sections above, and a review that names the shape and points at the remedy teaches faster than a comment that says \"please improve\".</p>\n<h2>Habits that keep a suite healthy</h2>\n<p>Keep tests close to the code they cover, in the same package, so they can use package-private members without opening the production API. Name the class after what it tests, and keep one behavior per method. Use literal expected values, calculated by hand or taken from a specification, rather than values computed from the code under test. Prefer real objects to mocks for anything cheap and deterministic, and use a mock for the boundary you do not own. Run the whole suite before every push, and treat a slow or flaky test as a defect with an owner, not as weather. When a test is deleted because the behavior is gone, say so in the commit message, and when a bug is fixed, the first commit is the failing test.</p>\n<p>Finally, remember what the framework cannot supply. JUnit gives you a place to write the test and a runner to execute it, and a good suite is the result of what you choose to test. The strategy of which tests to write, where, and against what, is the subject of <a href=\"/library/java-testing-strategy-practical\">a practical Java testing strategy</a>, and the two pages are meant to be read together.</p>\n<h2>Where JUnit is the wrong tool</h2>\n<p>JUnit runs tests; it does not decide which ones to write. A suite of fast, isolated unit tests will not catch a wrong SQL query or a broken serialization format, which need integration tests against real components. It is also not a benchmarking tool: use JMH for timing. And if you keep JUnit 4 tests you cannot migrate yet, keep the Vintage engine on the classpath and move test classes across one at a time. The <a href=\"https://junit.org/junit5/docs/current/api/\">Jupiter API documentation</a> documents the behavior in detail.</p>","date_published":"2026-11-14T04:21:31+00:00","tags":["JUnit"]},{"id":"https://javahacks.dev/library/java-testing-strategy-practical","url":"https://javahacks.dev/library/java-testing-strategy-practical","title":"A Practical Java Testing Strategy for Spring Boot Services","summary":"Decide what to unit test, what to run against real infrastructure and what to mock, with a layered plan that keeps a Spring Boot suite fast.","content_html":"<p>Teams rarely have too few tests. They have the wrong ones: hundreds of mock-heavy unit tests that pass when the code is broken, and three full-context tests that take four minutes and fail on a port conflict. A strategy is a decision about where each kind of risk gets caught. This guide lays out one for a Spring Boot 4 service on JDK 25 that talks to PostgreSQL, and explains where it breaks. The framework details live in <a href=\"/library/junit-5-handbook\">the JUnit 5 handbook</a>, and the Spring side is documented in the <a href=\"https://docs.spring.io/spring-boot/reference/testing/index.html\">Spring Boot testing reference</a>.</p>\n<h2>Match the test to the risk</h2>\n<table><thead><tr><th>Risk</th><th>Cheapest test that catches it</th></tr></thead><tbody><tr><td>A pricing rule is wrong</td><td>Unit test on the domain class</td></tr><tr><td>A request is bound or validated wrongly</td><td><code>@WebMvcTest</code> slice</td></tr><tr><td>A query returns the wrong rows</td><td>Repository test against a real PostgreSQL</td></tr><tr><td>A message is serialized wrongly</td><td>Integration test against a real broker</td></tr><tr><td>Two services disagree on a contract</td><td>Contract test</td></tr><tr><td>A journey breaks across the whole system</td><td>End-to-end test</td></tr></tbody></table>\n<p>The table is the strategy. Everything else is how to implement each row cheaply.</p>\n<h2>Test logic without Spring</h2>\n<p>Business rules belong in plain classes that take their collaborators in a constructor. Then the test is an ordinary object:</p>\n<pre><code class=\"language-java\">class DiscountPolicyTest {\n\n    private final DiscountPolicy policy = new DiscountPolicy(Clock.fixed(\n            Instant.parse(\"2026-03-14T10:00:00Z\"), ZoneOffset.UTC));\n\n    @Test\n    void appliesWeekendRateOnSaturday() {\n        assertEquals(10, policy.percentFor(new Customer(\"ana\", Tier.GOLD)));\n    }\n}</code></pre>\n<p>No context starts, so this runs in milliseconds, and you can have thousands. A fixed <code>Clock</code> passed in turns time into an input. Code that calls <code>Instant.now()</code> internally cannot be tested like this, which is a good reason to inject the clock.</p>\n<h2>Test the wiring with slices</h2>\n<p>A slice loads a part of the context. <code>@WebMvcTest</code> loads controllers, advice, converters and filters; <code>@DataJpaTest</code> loads repositories and an <code>EntityManager</code>. They check what unit tests cannot: that a path variable binds, that validation returns <code>400</code>, that a derived query method parses. If the context fails to build, <a href=\"/library/failed-load-applicationcontext-fix-spring-boot\">Failed to load ApplicationContext</a> lists the causes in the order to check them.</p>\n<h2>Use the real database</h2>\n<p>An in-memory H2 database accepts SQL that PostgreSQL rejects and ignores locking behavior entirely. Run the real engine, using <a href=\"https://testcontainers.com/\">Testcontainers</a>:</p>\n<pre><code class=\"language-java\">@DataJpaTest\n@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)\n@Testcontainers\nclass OrderRepositoryTest {\n\n    @Container\n    @ServiceConnection\n    static PostgreSQLContainer&lt;?&gt; postgres = new PostgreSQLContainer&lt;&gt;(\"postgres:17\");\n\n    @Autowired OrderRepository orders;\n\n    @Test\n    void findsOpenOrdersForCustomer() {\n        // save fixtures, query, assert\n    }\n}</code></pre>\n<p><code>@ServiceConnection</code> wires the container's URL into the Spring datasource without property plumbing. The first run pulls the image, and later runs reuse it. If Docker is not reachable, the test fails at startup with <a href=\"/library/could-not-find-valid-docker-environment\">Could not find a valid Docker environment</a>. Share one container across classes with a static singleton or the reuse option so you pay the startup once.</p>\n<h2>Mock the edges, not the middle</h2>\n<p>Mock what you do not own or cannot run cheaply: an HTTP client to a payment provider, a clock, a random source. Do not mock your own value objects or domain services, because a mock encodes your assumption about their behavior, and the assumption is what you are trying to test. The detailed rules are in <a href=\"/library/mock-java-leave-real-tests\">what to mock and what to leave real</a>, and the vocabulary is in <a href=\"/library/test-doubles-java-mocks-stubs-fakes\">test doubles explained</a>. Strict stubbing in Mockito flags stubs that are never used, which is how [<code>UnnecessaryStubbingException</code>](/library/unnecessarystubbingexception-fix-mockito-junit-5) catches a test that stopped testing what it claims to.</p>\n<h2>Keep end-to-end tests few</h2>\n<p>Each end-to-end test starts the whole system, so it is slow and fails for reasons unrelated to your change: a port, a clock, a downstream. Keep three to ten covering the journeys that earn money, and run them in a separate stage. Everything else you were tempted to cover end to end can be covered one layer down at a fraction of the cost.</p>\n<h2>The pyramid, and where it bends</h2>\n<p>The usual picture is a wide base of unit tests, fewer integration tests and a narrow top. <a href=\"/library/test-pyramid-java-services-where-breaks\">The test pyramid for Java services</a> explains where that shape stops matching a service that is mostly glue between a database and a queue. In those services, integration tests against real infrastructure carry the weight, and the unit layer shrinks. Let the risk table above, not the picture, decide.</p>\n<h2>Suite time is a requirement</h2>\n<p>Set a budget: unit tests under 30 seconds, the full local suite under five minutes. When the suite exceeds what a developer will run before pushing, the tests stop being run. Fix that by moving cases down a layer, sharing containers and enabling <a href=\"/library/junit-5-handbook\">parallel execution</a> only once tests are independent.</p>\n<h2>A sample service and what each layer covers</h2>\n<p>Abstract advice is easy to nod at. So take one concrete service, an order API with a database, a payment client and a message producer, and assign its risks to layers. The class names are illustrative:</p>\n<table><thead><tr><th>Class</th><th>What can go wrong</th><th>Layer</th></tr></thead><tbody><tr><td><code>DiscountPolicy</code>, <code>Money</code>, <code>Order</code></td><td>Wrong arithmetic, invalid state transitions</td><td>Unit</td></tr><tr><td><code>OrderController</code></td><td>Binding, validation, status codes, security rules</td><td><code>@WebMvcTest</code></td></tr><tr><td><code>OrderRepository</code></td><td>Derived queries, JPQL, mapping, migrations</td><td><code>@DataJpaTest</code> with a real database</td></tr><tr><td><code>PaymentClient</code></td><td>Request shape, timeouts, error mapping</td><td>Test against a stubbed HTTP server</td></tr><tr><td><code>OrderEventsPublisher</code></td><td>Serialization, topic, key</td><td>Test against a real broker</td></tr><tr><td><code>POST /orders</code> through the whole stack</td><td>Wiring across all of the above</td><td>A few integration tests</td></tr><tr><td>Checkout in a browser</td><td>The journey as a customer sees it</td><td>One or two end-to-end tests</td></tr></tbody></table>\n<p>Count the classes in each row of your own service and the numbers write the plan: most of the volume is in the first row, most of the risk that the first row cannot see is in the middle rows, and the last two rows exist to prove that the pieces are connected.</p>\n<h2>Unit tests that survive refactoring</h2>\n<p>A unit test fails for a good reason when the behavior changes, and for a bad one when the structure does. Bad failures come from asserting how the code works instead of what it produces. Compare two tests of the same discount rule:</p>\n<pre><code class=\"language-java\">// brittle: knows the implementation\n@Test\nvoid callsRepositoryAndAppliesRate() {\n    when(rates.rateFor(GOLD)).thenReturn(new BigDecimal(\"0.10\"));\n    policy.priceFor(order);\n    verify(rates).rateFor(GOLD);\n    verifyNoMoreInteractions(rates);\n}\n\n// resilient: knows the rule\n@Test\nvoid goldCustomersPayTenPercentLess() {\n    Order order = anOrder().forCustomer(gold()).withLine(\"sku-1\", 2, \"50.00\").build();\n\n    Money price = policy.priceFor(order);\n\n    assertThat(price).isEqualTo(Money.of(\"90.00\"));\n}</code></pre>\n<p>The second test survives the day someone replaces the repository with a lookup table, and the first one does not. Use a builder, as above, so that each test states only the facts it cares about:</p>\n<pre><code class=\"language-java\">final class OrderBuilder {\n\n    private CustomerId customer = new CustomerId(\"c-default\");\n    private final List&lt;OrderLine&gt; lines = new ArrayList&lt;&gt;();\n\n    static OrderBuilder anOrder() { return new OrderBuilder(); }\n\n    OrderBuilder forCustomer(Customer c) { this.customer = c.id(); return this; }\n\n    OrderBuilder withLine(String sku, int quantity, String unitPrice) {\n        lines.add(new OrderLine(new Sku(sku), quantity, Money.of(unitPrice)));\n        return this;\n    }\n\n    Order build() { return new Order(OrderId.next(), customer, lines); }\n}</code></pre>\n<p>A test with a ten-line setup of constructor arguments hides the one value that matters, and the builder keeps it in view. Parameterized tests are the other tool that keeps a rule's table readable:</p>\n<pre><code class=\"language-java\">@ParameterizedTest(name = \"{0} items for {1} customer costs {2}\")\n@CsvSource({\n    \"1,  STANDARD, 50.00\",\n    \"10, STANDARD, 450.00\",\n    \"10, GOLD,     405.00\",\n    \"0,  GOLD,     0.00\"\n})\nvoid volumeAndTierDiscounts(int quantity, Tier tier, String expected) {\n    Order order = anOrder().forCustomer(customerOf(tier)).withLine(\"sku-1\", quantity, \"50.00\").build();\n    assertThat(policy.priceFor(order)).isEqualTo(Money.of(expected));\n}</code></pre>\n<p>For rules with a large input space, a property-based test states an invariant and lets a library generate the cases. With jqwik, \"a discount never makes the price negative or higher than the original\" is three lines, and it finds the zero or the overflow that nobody thought to write down.</p>\n<h2>Web slices that catch what unit tests cannot</h2>\n<p>A controller unit test with mocks passes when the request never binds. A <code>@WebMvcTest</code> runs the real MVC machinery against a mocked service, so binding, validation, serialization and security rules are exercised:</p>\n<pre><code class=\"language-java\">@WebMvcTest(OrderController.class)\nclass OrderControllerTest {\n\n    @Autowired MockMvc mvc;\n    @MockitoBean OrderService orders;\n\n    @Test\n    @WithMockUser(roles = \"CUSTOMER\")\n    void createReturns201WithLocation() throws Exception {\n        when(orders.create(any())).thenReturn(new OrderView(42L, \"PLACED\", new BigDecimal(\"99.00\")));\n\n        mvc.perform(post(\"/orders\")\n                .with(csrf())\n                .contentType(MediaType.APPLICATION_JSON)\n                .content(\"\"\"\n                    {\"customerId\":\"c-1\",\"lines\":[{\"sku\":\"sku-1\",\"quantity\":2}]}\"\"\"))\n           .andExpect(status().isCreated())\n           .andExpect(header().string(\"Location\", endsWith(\"/orders/42\")))\n           .andExpect(jsonPath(\"$.status\").value(\"PLACED\"));\n    }\n\n    @Test\n    @WithMockUser(roles = \"CUSTOMER\")\n    void rejectsAnEmptyOrderWithProblemDetails() throws Exception {\n        mvc.perform(post(\"/orders\")\n                .with(csrf())\n                .contentType(MediaType.APPLICATION_JSON)\n                .content(\"\"\"\n                    {\"customerId\":\"c-1\",\"lines\":[]}\"\"\"))\n           .andExpect(status().isBadRequest())\n           .andExpect(content().contentTypeCompatibleWith(\"application/problem+json\"));\n    }\n\n    @Test\n    void anonymousCallersAreRejected() throws Exception {\n        mvc.perform(post(\"/orders\").contentType(MediaType.APPLICATION_JSON).content(\"{}\"))\n           .andExpect(status().isUnauthorized());\n    }\n}</code></pre>\n<p>Three tests, three kinds of fault: a mapping that returns the wrong status, a validation rule that is missing, and a security rule that was never applied. Each failure would otherwise be found by a person with a browser. When a slice fails to start, read the first <code>Caused by</code>, which almost always names a bean the slice did not load, and import it with <code>@Import</code>, as described in <a href=\"/library/spring-boot-test-slices-use-properly\">test slices</a>.</p>\n<h2>Persistence tests against the engine you ship</h2>\n<p>The repository test earlier shows the container. What goes inside it matters more. Test the queries you wrote, not the ones Spring Data derived for you, and test the migration, since a schema that differs from the mapping is a production incident:</p>\n<pre><code class=\"language-java\">@DataJpaTest\n@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)\n@Import(Containers.class)\nclass OrderRepositoryTest {\n\n    @Autowired OrderRepository orders;\n    @Autowired TestEntityManager em;\n\n    @Test\n    void findsOnlyOpenOrdersOfTheCustomerNewestFirst() {\n        Customer ana = em.persist(aCustomer(\"ana\"));\n        Customer bob = em.persist(aCustomer(\"bob\"));\n        em.persist(anOrderFor(ana).status(OPEN).createdAt(\"2026-03-01T10:00:00Z\").build());\n        em.persist(anOrderFor(ana).status(OPEN).createdAt(\"2026-03-02T10:00:00Z\").build());\n        em.persist(anOrderFor(ana).status(SHIPPED).build());\n        em.persist(anOrderFor(bob).status(OPEN).build());\n        em.flush();\n        em.clear();\n\n        List&lt;Order&gt; found = orders.openFor(ana.getId());\n\n        assertThat(found).extracting(o -&gt; o.getCreatedAt().toString())\n            .containsExactly(\"2026-03-02T10:00:00Z\", \"2026-03-01T10:00:00Z\");\n    }\n}</code></pre>\n<p>The <code>flush</code> and <code>clear</code> pair is deliberate. Without it, the query returns the entities that are already in the first-level cache and never reaches the database, and a wrong query still passes. Run Flyway migrations in the same test configuration, and set <code>spring.jpa.hibernate.ddl-auto=validate</code>, so the test fails when the mapping and the schema disagree. Add the statement-counting assertion for any query that feeds a list, as shown in <a href=\"/library/detect-n-plus-1-queries-tests\">detecting N plus 1 queries in tests</a>.</p>\n<h2>One container configuration, shared</h2>\n<p>Containers are the expensive part of integration tests, so start each once per run and share it. Put them in one configuration class that every test imports:</p>\n<pre><code class=\"language-java\">@TestConfiguration(proxyBeanMethods = false)\npublic class Containers {\n\n    @Bean\n    @ServiceConnection\n    PostgreSQLContainer&lt;?&gt; postgres() {\n        return new PostgreSQLContainer&lt;&gt;(\"postgres:17\").withReuse(true);\n    }\n\n    @Bean\n    @ServiceConnection\n    KafkaContainer kafka() {\n        return new KafkaContainer(DockerImageName.parse(\"apache/kafka:3.9.0\"));\n    }\n}</code></pre>\n<p>Every test that imports <code>Containers</code> with the same other annotations shares a Spring context and the containers behind it, as covered in <a href=\"/library/spring-test-context-caching-cache-speed\">caching the Spring test context</a>. <code>withReuse(true)</code> lets a developer's local run keep the container between runs when the user has enabled reuse in their Testcontainers configuration, which turns a ten-second startup into an instant one.</p>\n<h2>The HTTP boundary: stub the server, not the client</h2>\n<p>A mocked <code>PaymentClient</code> proves that the service calls the mock. A stubbed HTTP server proves that the real client builds the right request and understands the real response, including the bad ones:</p>\n<pre><code class=\"language-java\">@SpringBootTest\n@Import(Containers.class)\n@WireMockTest(httpPort = 8089)\nclass PaymentClientIT {\n\n    @Autowired PaymentClient payments;\n\n    @DynamicPropertySource\n    static void urls(DynamicPropertyRegistry registry) {\n        registry.add(\"payments.base-url\", () -&gt; \"http://localhost:8089\");\n    }\n\n    @Test\n    void sendsTheChargeAndReadsTheReceipt() {\n        stubFor(post(\"/charges\")\n            .withHeader(\"Idempotency-Key\", matching(\".+\"))\n            .withRequestBody(matchingJsonPath(\"$.amount\", equalTo(\"99.00\")))\n            .willReturn(okJson(\"\"\"\n                {\"id\":\"ch_1\",\"status\":\"succeeded\"}\"\"\")));\n\n        Receipt receipt = payments.charge(new Charge(\"order-1\", Money.of(\"99.00\")));\n\n        assertThat(receipt.status()).isEqualTo(\"succeeded\");\n    }\n\n    @Test\n    void mapsAGatewayTimeoutToAPaymentUnavailableError() {\n        stubFor(post(\"/charges\").willReturn(aResponse().withFixedDelay(3000).withStatus(200)));\n\n        assertThrows(PaymentUnavailable.class,\n            () -&gt; payments.charge(new Charge(\"order-2\", Money.of(\"5.00\"))));\n    }\n}</code></pre>\n<p>The second test is the one nobody writes and the one that matters: what the service does when the dependency is slow. Add a case for a <code>500</code>, a malformed body and a connection reset. These are the failures production will deliver, and a test double that always succeeds hides them all.</p>\n<h2>Asynchronous behavior without sleeps</h2>\n<p>A message published to a broker arrives later. The wrong test sleeps for two seconds and hopes. The right one waits for a condition, with a timeout:</p>\n<pre><code class=\"language-java\">@Test\nvoid placingAnOrderPublishesAnEvent() {\n    ResponseEntity&lt;Void&gt; response = rest.postForEntity(\"/orders\", newOrder(), Void.class);\n    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);\n\n    await().atMost(Duration.ofSeconds(10)).untilAsserted(() -&gt; {\n        List&lt;ConsumerRecord&lt;String, String&gt;&gt; records = consumer.received(\"orders\");\n        assertThat(records).hasSize(1);\n        assertThat(records.get(0).value()).contains(\"\\\"event\\\":\\\"OrderPlaced\\\"\");\n    });\n}</code></pre>\n<p>Awaitility polls until the assertion passes or the timeout expires, so a fast system finishes quickly and a slow one gets a fair chance. Keep the timeout generous, because it only costs time on failure. A test that needs <code>Thread.sleep</code> to pass is a flaky test with a delay, and the first thing to look for in a flaky suite.</p>\n<h2>Contracts between services</h2>\n<p>When two services agree on a request and a response, each side's tests can drift while both stay green. A contract test pins the agreement in a file both sides run against. The lightest version needs no framework: a shared JSON example that the provider's test must produce and the consumer's test must parse:</p>\n<pre><code class=\"language-java\">// provider side: the response must match the agreed example\n@Test\nvoid orderResponseMatchesTheContract() throws Exception {\n    String expected = Files.readString(Path.of(\"src/test/resources/contracts/order-response.json\"));\n    mvc.perform(get(\"/orders/42\"))\n       .andExpect(status().isOk())\n       .andExpect(content().json(expected, JsonCompareMode.STRICT));\n}\n\n// consumer side: the same file must deserialize into the client's type\n@Test\nvoid clientUnderstandsTheContract() throws Exception {\n    String json = Files.readString(Path.of(\"src/test/resources/contracts/order-response.json\"));\n    OrderView view = new ObjectMapper().findAndRegisterModules().readValue(json, OrderView.class);\n    assertThat(view.id()).isEqualTo(42L);\n}</code></pre>\n<p>Keep the file in a place both repositories read, such as a small shared artifact. For many consumers, Spring Cloud Contract or Pact automate the same idea and add a broker to track which version of which consumer expects what. Pick the tool when the manual file approach starts to hurt, not before.</p>\n<h2>Check the tests themselves</h2>\n<p>Coverage says which lines ran, and nothing about whether a test would notice if the line were wrong. Mutation testing changes the code in small ways, such as flipping a comparison or deleting a call, and reports the changes the suite failed to catch:</p>\n<pre><code class=\"language-xml\">&lt;plugin&gt;\n  &lt;groupId&gt;org.pitest&lt;/groupId&gt;\n  &lt;artifactId&gt;pitest-maven&lt;/artifactId&gt;\n  &lt;configuration&gt;\n    &lt;targetClasses&gt;&lt;param&gt;dev.javahacks.shop.domain.*&lt;/param&gt;&lt;/targetClasses&gt;\n    &lt;mutationThreshold&gt;80&lt;/mutationThreshold&gt;\n  &lt;/configuration&gt;\n&lt;/plugin&gt;</code></pre>\n<pre><code class=\"language-bash\">./mvnw org.pitest:pitest-maven:mutationCoverage</code></pre>\n<p>Run it on the domain package, where logic lives, and not on controllers and configuration, where it produces noise. Treat a surviving mutant as a question: either a test is missing, or the code has a behavior nobody cares about, and both are worth knowing. Do not put a score on a dashboard as a target, since a number someone is rewarded for becomes a number someone games.</p>\n<h2>Organizing the build around the strategy</h2>\n<p>The layers should map to build stages, so that feedback arrives in order of cost. Unit tests run in the compile phase of every build, and integration tests run after, under a separate plugin:</p>\n<pre><code class=\"language-xml\">&lt;plugin&gt;\n  &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;\n  &lt;configuration&gt;\n    &lt;excludes&gt;&lt;exclude&gt;**/*IT.java&lt;/exclude&gt;&lt;/excludes&gt;\n  &lt;/configuration&gt;\n&lt;/plugin&gt;\n&lt;plugin&gt;\n  &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;\n  &lt;executions&gt;\n    &lt;execution&gt;\n      &lt;goals&gt;&lt;goal&gt;integration-test&lt;/goal&gt;&lt;goal&gt;verify&lt;/goal&gt;&lt;/goals&gt;\n    &lt;/execution&gt;\n  &lt;/executions&gt;\n&lt;/plugin&gt;</code></pre>\n<p>With this split, <code>./mvnw test</code> runs in seconds and is what a developer runs on every change, <code>./mvnw verify</code> runs everything and is what CI runs on every push, and a pipeline can fail fast on the unit stage before it pays for containers. Record the time of each stage in the build log and review it monthly. The numbers tell you when the suite is turning into the thing nobody runs. The details of the Maven side are in <a href=\"/library/maven-surefire-failsafe-junit-run\">Surefire, Failsafe and JUnit</a>.</p>\n<h2>Flaky tests are a defect with an owner</h2>\n<p>A test that fails one run in fifty teaches the team to rerun. Handle each one the day it appears. Quarantine it with a tag so that it stops blocking others, file it with the failure output attached, and fix the cause: shared state between tests, an unseeded random source, time, ordering, or a race in the code under test, which is the case where the test is the only thing telling the truth. Never add an automatic retry to the whole suite, because it converts a signal into noise and a real intermittent bug into a pass.</p>\n<h2>Rolling the strategy out on an existing suite</h2>\n<p>Nobody starts from zero, so the practical question is what to do on Monday. A sequence that has worked for teams with a slow, distrusted suite:</p>\n<ol><li>Measure first. Record total time, time per layer, the number of tests and the failures per week for a month.</li><li>Fix the flaky tests and delete the dead ones. A smaller trusted suite is better than a larger doubted one.</li><li>Move the slowest full-context tests to slices where the risk allows, and share the containers.</li><li>Add the missing middle: a real-database repository test for each hand-written query, and a stubbed-server test for each outbound client with the failure cases.</li><li>Write down the layer table for the service, one page, and use it in code review: \"which layer should catch this?\"</li><li>Set the time budget and watch it. When a new test pushes the suite over, the author finds the one to move down.</li></ol>\n<p>At the end of a quarter, the suite should be faster, the failures should point at real problems and a red build should mean something. That, and not the shape of a diagram, is the measure of the strategy.</p>\n<h2>Names and structure that make failures readable</h2>\n<p>When a test fails in CI, the report shows its name before anything else, so the name should state the behavior and the condition. <code>test1</code> and <code>shouldWork</code> fail without telling anyone what broke. A test class named after the class under test, with method names that read as sentences, turns the build log into documentation:</p>\n<pre><code class=\"language-java\">class OrderTest {\n\n    @Nested\n    class WhenPlacing {\n\n        @Test\n        void anEmptyOrderIsRejected() { /* ... */ }\n\n        @Test\n        void aPlacedOrderCannotGainLines() { /* ... */ }\n\n        @Test\n        void aPlacedOrderPublishesOneEvent() { /* ... */ }\n    }\n\n    @Nested\n    class WhenCancelling {\n\n        @Test\n        void aShippedOrderCannotBeCancelled() { /* ... */ }\n    }\n}</code></pre>\n<p>Inside each test, keep the three parts visible, in order: set up the situation, perform one action, assert on the outcome. A test with two actions is two tests, and a test with a loop and an <code>if</code> has logic that nobody tests. Prefer AssertJ's fluent assertions for their failure messages, which show the expected and actual values in full, and give custom assertions to the types you assert on often.</p>\n<h2>Test the configuration, because it fails in production first</h2>\n<p>A service that compiles and passes its tests can still fail to start, since the failure lives in properties, profiles and bean wiring. One test that boots the real application with the production-like profile finds most of it:</p>\n<pre><code class=\"language-java\">@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\n@Import(Containers.class)\n@ActiveProfiles(\"prod-like\")\nclass ApplicationStartsTest {\n\n    @Autowired ApplicationContext context;\n    @Autowired TestRestTemplate rest;\n\n    @Test\n    void contextLoadsAndHealthIsUp() {\n        assertThat(context.getBeansOfType(OrderService.class)).hasSize(1);\n\n        ResponseEntity&lt;String&gt; health = rest.getForEntity(\"/actuator/health\", String.class);\n\n        assertThat(health.getStatusCode()).isEqualTo(HttpStatus.OK);\n        assertThat(health.getBody()).contains(\"\\\"status\\\":\\\"UP\\\"\");\n    }\n}</code></pre>\n<p>It is slow compared with a unit test and cheap compared with a failed deployment. Pair it with a test that checks the properties your code requires are bound, by loading the <code>@ConfigurationProperties</code> class with a minimal context and asserting that validation rejects a missing value. A required setting that fails at startup, with a named property in the message, is a gift to whoever deploys it at night.</p>\n<h2>Architecture rules as tests</h2>\n<p>Some decisions are about structure, and a code review is a weak place to enforce them. ArchUnit expresses them as tests that run with everything else:</p>\n<pre><code class=\"language-java\">@AnalyzeClasses(packages = \"dev.javahacks.shop\", importOptions = ImportOption.DoNotIncludeTests.class)\nclass ArchitectureTest {\n\n    @ArchTest\n    static final ArchRule domainDoesNotDependOnSpring =\n        noClasses().that().resideInAPackage(\"..domain..\")\n            .should().dependOnClassesThat().resideInAPackage(\"org.springframework..\");\n\n    @ArchTest\n    static final ArchRule controllersDoNotTouchRepositories =\n        noClasses().that().resideInAPackage(\"..web..\")\n            .should().dependOnClassesThat().resideInAPackage(\"..persistence..\");\n}</code></pre>\n<p>The first rule is what keeps the domain testable without a context, which is the foundation of the whole strategy: the day a domain class gains an <code>@Autowired</code>, the fast layer starts to decay, and this test says so. Keep the rule list short and tied to decisions the team made on purpose.</p>\n<h2>What not to test</h2>\n<p>Part of a strategy is the list of things you decline to test, and writing it down prevents a slow drift into writing tests for coverage. Do not test getters, setters and constructors that hold no logic. Do not test the framework: asserting that <code>@Transactional</code> rolls back, or that Spring Data can save an entity, repeats the framework's own suite. Do not test private methods directly; if one is complicated enough to want a test, it wants to be its own class. And do not copy the implementation into the test, as in a test that recomputes the expected discount with the same formula, since a bug in the formula appears on both sides and the test agrees with it. Use literal expected values worked out by hand or taken from the business rule.</p>\n<h2>Where this plan does not fit</h2>\n<p>This layout assumes a request-response service with a relational database. A data pipeline wants property-based and golden-file tests; a UI-heavy application needs browser tests that this strategy keeps minimal on purpose. A library should invest in unit tests and a compatibility matrix instead of containers. In each case, keep the risk table and change the rows.</p>","date_published":"2026-11-14T04:20:31+00:00","tags":["Testing"]},{"id":"https://javahacks.dev/library/vaadin-web-ui-guide-building-uis","url":"https://javahacks.dev/library/vaadin-web-ui-guide-building-uis","title":"Vaadin Web UI Guide to Building Interfaces in Pure Java","summary":"Build a Vaadin web UI in Java: views, layouts, Binder forms, lazy Grids, push updates, security, testing and the production build in one worked app.","content_html":"<p>Most Java developers who need a web interface face the same fork. Learn a second ecosystem (a JavaScript framework, a build chain, a REST contract between two codebases and two sets of tests), or generate server-rendered pages and live with the limits of forms and page reloads. Vaadin Flow takes a third route: you write the interface in Java, with components such as <code>TextField</code>, <code>Grid</code> and <code>Dialog</code>, and a thin client in the browser draws them. There is no DOM code, no JSON endpoints between your UI and your service layer, and no second language. For internal tools, admin consoles, back-office applications and data-heavy dashboards, that is a large amount of work you do not do.</p>\n<p>This guide builds one application from nothing and covers the whole life of a Vaadin project: the server-side model and why it shapes everything, views and routing, layouts, forms with validation, a lazily loaded <code>Grid</code>, dialogs, theming, push updates, security, testing, memory and the production build. The application is a small customer manager on Spring Boot 4 and Java 25 with Vaadin 25. Where a topic has its own post, the section links to it for the deeper treatment, so use this page as the map. The example code compiles against the Flow APIs named in each section, but verify details against the <a href=\"https://vaadin.com/docs\">Vaadin documentation</a> for your exact version, since component APIs gain methods between releases.</p>\n<h2>How Vaadin Flow works</h2>\n<p>Everything else in this guide follows from one fact: the component tree lives on the server. When your code calls <code>new Button(\"Save\")</code>, an object is created in the JVM, in the user's session. Vaadin sends a description of that object to the browser, where a small JavaScript client renders it as web components. When the user clicks, the client sends an event to the server, your Java listener runs, you change some components, and Vaadin sends back only what changed. The browser holds a rendering, not the application state. The long version is in <a href=\"/library/vaadin-flow-server-side-model-works\">how the Flow server-side model works</a>.</p>\n<p>This design has consequences you should hold in mind from the start:</p>\n<table><thead><tr><th>Consequence</th><th>What it means for you</th></tr></thead><tbody><tr><td>Your listener code runs on the server</td><td>It can call services, repositories and security checks directly; there is no API layer to design</td></tr><tr><td>State lives in a session</td><td>Memory grows with concurrent users, see the memory section below</td></tr><tr><td>Every interaction is a round trip</td><td>A slow server call makes the UI feel slow; keep listeners fast and move long work to background threads</td></tr><tr><td>The client is generic</td><td>Nothing about your business rules exists in the browser, which is also a security benefit</td></tr><tr><td>Components are Java objects</td><td>You can refactor, test and reuse a UI with the tools you use for any Java code</td></tr></tbody></table>\n<p>Vaadin also offers Hilla, a variant where the UI is written in React and talks to typed endpoints, covered in <a href=\"/library/vaadin-hilla-use-react\">Hilla with React</a>. Everything below is Flow. If your team writes React already, ask whether you want this at all, see <a href=\"/library/vaadin-vs-react-spring-boot-internal\">Vaadin against React and Spring Boot</a>.</p>\n<h2>Set up the project</h2>\n<p>Start from <code>start.vaadin.com</code> or generate a Spring Boot project and add the Vaadin starter. The pieces that matter in <code>pom.xml</code> are the BOM, the Spring Boot starter and the production profile:</p>\n<pre data-filename=\"pom.xml\"><code class=\"language-xml\">&lt;properties&gt;\n  &lt;java.version&gt;25&lt;/java.version&gt;\n  &lt;vaadin.version&gt;25.0.0&lt;/vaadin.version&gt;\n&lt;/properties&gt;\n\n&lt;dependencyManagement&gt;\n  &lt;dependencies&gt;\n    &lt;dependency&gt;\n      &lt;groupId&gt;com.vaadin&lt;/groupId&gt;\n      &lt;artifactId&gt;vaadin-bom&lt;/artifactId&gt;\n      &lt;version&gt;${vaadin.version}&lt;/version&gt;\n      &lt;type&gt;pom&lt;/type&gt;\n      &lt;scope&gt;import&lt;/scope&gt;\n    &lt;/dependency&gt;\n  &lt;/dependencies&gt;\n&lt;/dependencyManagement&gt;\n\n&lt;dependencies&gt;\n  &lt;dependency&gt;\n    &lt;groupId&gt;com.vaadin&lt;/groupId&gt;\n    &lt;artifactId&gt;vaadin-spring-boot-starter&lt;/artifactId&gt;\n  &lt;/dependency&gt;\n  &lt;dependency&gt;\n    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;\n    &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;\n  &lt;/dependency&gt;\n  &lt;dependency&gt;\n    &lt;groupId&gt;com.h2database&lt;/groupId&gt;\n    &lt;artifactId&gt;h2&lt;/artifactId&gt;\n    &lt;scope&gt;runtime&lt;/scope&gt;\n  &lt;/dependency&gt;\n&lt;/dependencies&gt;\n\n&lt;profiles&gt;\n  &lt;profile&gt;\n    &lt;id&gt;production&lt;/id&gt;\n    &lt;build&gt;\n      &lt;plugins&gt;\n        &lt;plugin&gt;\n          &lt;groupId&gt;com.vaadin&lt;/groupId&gt;\n          &lt;artifactId&gt;vaadin-maven-plugin&lt;/artifactId&gt;\n          &lt;version&gt;${vaadin.version}&lt;/version&gt;\n          &lt;executions&gt;\n            &lt;execution&gt;\n              &lt;goals&gt;\n                &lt;goal&gt;build-frontend&lt;/goal&gt;\n              &lt;/goals&gt;\n            &lt;/execution&gt;\n          &lt;/executions&gt;\n        &lt;/plugin&gt;\n      &lt;/plugins&gt;\n    &lt;/build&gt;\n  &lt;/profile&gt;\n&lt;/profiles&gt;</code></pre>\n<p>Run <code>./mvnw spring-boot:run</code>, open <code>http://localhost:8080</code>, and the first start downloads and compiles the frontend, which takes a minute. Later starts are fast. The Spring wiring (beans in views, scopes, security integration) is in <a href=\"/library/vaadin-spring-boot-use\">Vaadin with Spring Boot</a>, and a shorter first-hour walkthrough is in <a href=\"/library/vaadin-tutorial-beginners-pure-java\">the beginners tutorial</a>.</p>\n<p>The data model for the example is one entity and a repository:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/Customer.java\"><code class=\"language-java\">import jakarta.persistence.Entity;\nimport jakarta.persistence.GeneratedValue;\nimport jakarta.persistence.Id;\nimport jakarta.validation.constraints.Email;\nimport jakarta.validation.constraints.NotBlank;\nimport jakarta.validation.constraints.Size;\n\n@Entity\npublic class Customer {\n\n    @Id @GeneratedValue\n    private Long id;\n\n    @NotBlank @Size(max = 80)\n    private String name;\n\n    @NotBlank @Email\n    private String email;\n\n    private String tier = \"STANDARD\";\n\n    public Long getId() { return id; }\n    public String getName() { return name; }\n    public void setName(String name) { this.name = name; }\n    public String getEmail() { return email; }\n    public void setEmail(String email) { this.email = email; }\n    public String getTier() { return tier; }\n    public void setTier(String tier) { this.tier = tier; }\n}</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/CustomerRepository.java\"><code class=\"language-java\">import org.springframework.data.domain.Page;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.data.jpa.repository.JpaRepository;\n\npublic interface CustomerRepository extends JpaRepository&lt;Customer, Long&gt; {\n\n    Page&lt;Customer&gt; findByNameContainingIgnoreCase(String name, Pageable pageable);\n\n    long countByNameContainingIgnoreCase(String name);\n}</code></pre>\n<p>A thin service sits between the views and the repository. Views should never touch repositories directly in a real application, because the service is where transactions and security belong:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/CustomerService.java\"><code class=\"language-java\">import org.springframework.data.domain.Page;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\n@Service\n@Transactional(readOnly = true)\npublic class CustomerService {\n\n    private final CustomerRepository repository;\n\n    public CustomerService(CustomerRepository repository) {\n        this.repository = repository;\n    }\n\n    public Page&lt;Customer&gt; search(String filter, Pageable page) {\n        return repository.findByNameContainingIgnoreCase(filter == null ? \"\" : filter, page);\n    }\n\n    public long count(String filter) {\n        return repository.countByNameContainingIgnoreCase(filter == null ? \"\" : filter);\n    }\n\n    @Transactional\n    public Customer save(Customer customer) {\n        return repository.save(customer);\n    }\n\n    @Transactional\n    public void delete(Customer customer) {\n        repository.delete(customer);\n    }\n}</code></pre>\n<h2>A view is a Java class</h2>\n<p>A page in Vaadin is a component class with a <code>@Route</code>. This is the whole definition of a page that greets the user:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/HelloView.java\"><code class=\"language-java\">import com.vaadin.flow.component.button.Button;\nimport com.vaadin.flow.component.notification.Notification;\nimport com.vaadin.flow.component.orderedlayout.VerticalLayout;\nimport com.vaadin.flow.component.textfield.TextField;\nimport com.vaadin.flow.router.PageTitle;\nimport com.vaadin.flow.router.Route;\n\n@Route(\"hello\")\n@PageTitle(\"Hello\")\npublic class HelloView extends VerticalLayout {\n\n    public HelloView() {\n        TextField name = new TextField(\"Your name\");\n        Button greet = new Button(\"Greet\", event -&gt; Notification.show(\"Hello, \" + name.getValue()));\n        add(name, greet);\n    }\n}</code></pre>\n<p>Open <code>/hello</code>, type a name and click: a notification appears, and your Java lambda ran on the server. Notice what is absent. There is no controller, no template, no JSON and no JavaScript. <code>VerticalLayout</code> is a container that stacks its children, and <code>add</code> appends components. <code>Button</code> takes a click listener as a lambda. That is the programming model for everything else.</p>\n<p>A few rules that save time:</p>\n<ul><li><strong>Views are created per navigation.</strong> Each visit constructs a new instance, so instance fields are per-user, per-visit state. Do not store shared data in them.</li><li><strong>Do the setup in the constructor, load data in lifecycle hooks.</strong> If you need route parameters or want to refresh on re-entry, implement <code>BeforeEnterObserver</code> or override <code>onAttach</code>.</li><li><strong>Components are cheap, listeners are the cost.</strong> Create as many components as the interface needs, but do not call a database inside a render loop.</li></ul>\n<h2>Layouts give pages a shared frame</h2>\n<p>Most applications have a header and navigation around the page content. In Vaadin that frame is a layout: a component that implements <code>RouterLayout</code>, and pages declare it with <code>@Route(value = \"...\", layout = MainLayout.class)</code>. The <code>AppLayout</code> component provides a drawer and navbar:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/MainLayout.java\"><code class=\"language-java\">import com.vaadin.flow.component.applayout.AppLayout;\nimport com.vaadin.flow.component.applayout.DrawerToggle;\nimport com.vaadin.flow.component.html.H1;\nimport com.vaadin.flow.component.icon.VaadinIcon;\nimport com.vaadin.flow.component.sidenav.SideNav;\nimport com.vaadin.flow.component.sidenav.SideNavItem;\n\npublic class MainLayout extends AppLayout {\n\n    public MainLayout() {\n        H1 title = new H1(\"Customer manager\");\n        title.getStyle().set(\"font-size\", \"var(--lumo-font-size-l)\").set(\"margin\", \"0\");\n        addToNavbar(new DrawerToggle(), title);\n\n        SideNav nav = new SideNav();\n        nav.addItem(new SideNavItem(\"Customers\", CustomerListView.class, VaadinIcon.USERS.create()));\n        nav.addItem(new SideNavItem(\"Dashboard\", DashboardView.class, VaadinIcon.CHART.create()));\n        addToDrawer(nav);\n    }\n}</code></pre>\n<p><code>SideNavItem</code> takes a view class, not a path string, so renaming a route does not break the menu. The navigation model, nested layouts, route parameters and <code>@RoutePrefix</code> are covered in <a href=\"/library/vaadin-routing-layouts-build-navigation\">routing and layouts</a>. One layout can wrap many views, and layouts can nest (a settings layout inside the main layout), which is how you build sections that share a sub-menu.</p>\n<h2>A list with a filter and a lazy Grid</h2>\n<p>The <code>Grid</code> is the component most business applications are built around. This view lists customers, with a search field and a button for adding one:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/CustomerListView.java\"><code class=\"language-java\">import com.vaadin.flow.component.button.Button;\nimport com.vaadin.flow.component.button.ButtonVariant;\nimport com.vaadin.flow.component.grid.Grid;\nimport com.vaadin.flow.component.grid.GridVariant;\nimport com.vaadin.flow.component.icon.VaadinIcon;\nimport com.vaadin.flow.component.orderedlayout.HorizontalLayout;\nimport com.vaadin.flow.component.orderedlayout.VerticalLayout;\nimport com.vaadin.flow.component.textfield.TextField;\nimport com.vaadin.flow.data.value.ValueChangeMode;\nimport com.vaadin.flow.router.PageTitle;\nimport com.vaadin.flow.router.Route;\nimport com.vaadin.flow.spring.data.VaadinSpringDataHelpers;\n\n@Route(value = \"\", layout = MainLayout.class)\n@PageTitle(\"Customers\")\npublic class CustomerListView extends VerticalLayout {\n\n    private final CustomerService service;\n    private final Grid&lt;Customer&gt; grid = new Grid&lt;&gt;(Customer.class, false);\n    private final TextField filter = new TextField();\n\n    public CustomerListView(CustomerService service) {\n        this.service = service;\n        setSizeFull();\n\n        filter.setPlaceholder(\"Filter by name\");\n        filter.setClearButtonVisible(true);\n        filter.setValueChangeMode(ValueChangeMode.LAZY);   // waits ~400 ms after the last key\n        filter.addValueChangeListener(e -&gt; grid.getDataProvider().refreshAll());\n\n        Button add = new Button(\"Add customer\", VaadinIcon.PLUS.create(), e -&gt; openEditor(new Customer()));\n        add.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n\n        grid.addThemeVariants(GridVariant.LUMO_ROW_STRIPES);\n        grid.addColumn(Customer::getName).setHeader(\"Name\").setSortable(true).setKey(\"name\");\n        grid.addColumn(Customer::getEmail).setHeader(\"Email\").setKey(\"email\");\n        grid.addColumn(Customer::getTier).setHeader(\"Tier\");\n        grid.addItemDoubleClickListener(e -&gt; openEditor(e.getItem()));\n\n        grid.setItems(query -&gt; service.search(\n                filter.getValue(),\n                VaadinSpringDataHelpers.toSpringPageRequest(query)).stream());\n\n        add(new HorizontalLayout(filter, add), grid);\n        expand(grid);\n    }\n\n    private void openEditor(Customer customer) {\n        new CustomerEditor(customer, service, () -&gt; grid.getDataProvider().refreshAll()).open();\n    }\n}</code></pre>\n<p>The important line is <code>grid.setItems(query -&gt; ...)</code>. This overload gives Vaadin a callback instead of a list. The grid asks for exactly the rows the browser is about to show, with an offset, a limit and the sort order, and <code>toSpringPageRequest</code> turns that into a Spring <code>Pageable</code>. A table of five million rows costs the same as one of fifty, because the server only ever loads a screenful. <code>ValueChangeMode.LAZY</code> matters too: without it, the filter would query on every keystroke. The pitfalls of lazy loading, such as counting, sorting by a nested property and stale pages, are in <a href=\"/library/vaadin-grid-lazy-loading-use\">lazy loading in the Grid</a>.</p>\n<p>When the dataset is small, a plain <code>grid.setItems(list)</code> is fine and simpler. Choose the callback form when the table can grow or when the query is expensive.</p>\n<h2>Forms with Binder and validation</h2>\n<p>Forms are where server-side UI frameworks usually get tedious. <code>Binder</code> handles the repetitive part: it connects fields to bean properties, converts types, validates and reports errors next to the field. <code>BeanValidationBinder</code> reads the Jakarta Validation annotations already on the entity, so the rules live in one place.</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/CustomerEditor.java\"><code class=\"language-java\">import com.vaadin.flow.component.button.Button;\nimport com.vaadin.flow.component.button.ButtonVariant;\nimport com.vaadin.flow.component.combobox.ComboBox;\nimport com.vaadin.flow.component.dialog.Dialog;\nimport com.vaadin.flow.component.formlayout.FormLayout;\nimport com.vaadin.flow.component.notification.Notification;\nimport com.vaadin.flow.component.textfield.EmailField;\nimport com.vaadin.flow.component.textfield.TextField;\nimport com.vaadin.flow.data.binder.BeanValidationBinder;\nimport com.vaadin.flow.data.binder.ValidationException;\nimport java.util.List;\n\npublic class CustomerEditor extends Dialog {\n\n    private final BeanValidationBinder&lt;Customer&gt; binder = new BeanValidationBinder&lt;&gt;(Customer.class);\n    private final Customer customer;\n\n    public CustomerEditor(Customer customer, CustomerService service, Runnable onSaved) {\n        this.customer = customer;\n        setHeaderTitle(customer.getId() == null ? \"New customer\" : \"Edit customer\");\n\n        TextField name = new TextField(\"Name\");\n        EmailField email = new EmailField(\"Email\");\n        ComboBox&lt;String&gt; tier = new ComboBox&lt;&gt;(\"Tier\", List.of(\"STANDARD\", \"GOLD\", \"PLATINUM\"));\n\n        binder.forField(name).asRequired(\"Name is required\").bind(\"name\");\n        binder.forField(email).asRequired(\"Email is required\").bind(\"email\");\n        binder.forField(tier).bind(\"tier\");\n        binder.readBean(customer);\n\n        add(new FormLayout(name, email, tier));\n\n        Button save = new Button(\"Save\", e -&gt; {\n            try {\n                binder.writeBean(customer);           // validates, then copies into the bean\n                service.save(customer);\n                onSaved.run();\n                close();\n                Notification.show(\"Saved\");\n            } catch (ValidationException ex) {\n                Notification.show(\"Fix the highlighted fields\");\n            }\n        });\n        save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);\n        getFooter().add(new Button(\"Cancel\", e -&gt; close()), save);\n    }\n}</code></pre>\n<p>Several things happen that you did not write. Type the wrong email and the <code>EmailField</code> shows the error under the field as you leave it. <code>asRequired</code> adds the required indicator and message. <code>writeBean</code> runs every validator and, on failure, marks each invalid field and throws; on success it copies values into the bean in one step. If you want to copy only when valid and also keep the bean untouched on failure, that is exactly what <code>writeBean</code> does, while <code>writeBeanIfValid</code> returns a boolean instead of throwing. The detail of converters (<code>StringToIntegerConverter</code>), cross-field validators and status labels is in <a href=\"/library/vaadin-binder-validation-build-forms\">Binder validation for forms</a>.</p>\n<p>One design rule: validate in the entity or service as well. <code>Binder</code> validation is a convenience for the user. A server-side check in the service is what protects the data when another caller reaches it.</p>\n<h2>Add a dashboard and a chart</h2>\n<p>A second view shows how views share services. It also uses only built-in components:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/DashboardView.java\"><code class=\"language-java\">import com.vaadin.flow.component.html.Div;\nimport com.vaadin.flow.component.html.H2;\nimport com.vaadin.flow.component.html.Span;\nimport com.vaadin.flow.component.orderedlayout.VerticalLayout;\nimport com.vaadin.flow.router.PageTitle;\nimport com.vaadin.flow.router.Route;\n\n@Route(value = \"dashboard\", layout = MainLayout.class)\n@PageTitle(\"Dashboard\")\npublic class DashboardView extends VerticalLayout {\n\n    public DashboardView(CustomerService service) {\n        add(new H2(\"Overview\"), stat(\"Customers\", String.valueOf(service.count(\"\"))));\n    }\n\n    private Div stat(String label, String value) {\n        Span number = new Span(value);\n        number.getStyle().set(\"font-size\", \"var(--lumo-font-size-xxxl)\").set(\"font-weight\", \"600\");\n        Span caption = new Span(label);\n        caption.getStyle().set(\"color\", \"var(--lumo-secondary-text-color)\");\n        Div box = new Div(number, new Div(caption));\n        box.getStyle().set(\"padding\", \"var(--lumo-space-m)\")\n                      .set(\"border\", \"1px solid var(--lumo-contrast-10pct)\")\n                      .set(\"border-radius\", \"var(--lumo-border-radius-l)\");\n        return box;\n    }\n}</code></pre>\n<p>The styles use Lumo custom properties, the design tokens of Vaadin's default theme, so the card follows the theme including dark mode. For real charts, Vaadin has a Charts component, see charts and dashboards.</p>\n<h2>Theming</h2>\n<p>Vaadin ships a theme called Lumo with a light and a dark variant, and every component exposes theme variants (<code>ButtonVariant.LUMO_PRIMARY</code>) and CSS custom properties (<code>--lumo-primary-color</code>). The practical rules for keeping a theme maintainable:</p>\n<ol><li>Change tokens, not components. Redefine <code>--lumo-primary-color</code> and spacing once, and every component follows.</li><li>Prefer theme variants to custom CSS. <code>LUMO_ERROR</code> and <code>LUMO_SMALL</code> are supported and survive upgrades.</li><li>Put one-off layout CSS in a style sheet attached to the view or app, not in <code>getStyle().set()</code> calls scattered across Java. The inline calls above are acceptable in small doses, and a maintenance cost in bulk.</li></ol>\n<p>The mechanics of attaching a theme, with the changes in recent versions, are in <a href=\"/library/vaadin-theme-style-application\">theming and styling</a>, and the list of changes in the current major version is in what is new in Vaadin 25.</p>\n<h2>Updating the UI from another thread</h2>\n<p>A UI is single-threaded per session: Vaadin locks the session while a listener runs. If a background thread wants to change a component, for example when a long report finishes, it must hand the change to the UI. Enable server push on the application class, and use <code>UI.access</code>:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/Application.java\"><code class=\"language-java\">import com.vaadin.flow.component.page.AppShellConfigurator;\nimport com.vaadin.flow.component.page.Push;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\n@Push\npublic class Application implements AppShellConfigurator {\n    public static void main(String[] args) {\n        SpringApplication.run(Application.class, args);\n    }\n}</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/ReportView.java\"><code class=\"language-java\">import com.vaadin.flow.component.UI;\nimport com.vaadin.flow.component.button.Button;\nimport com.vaadin.flow.component.html.Span;\nimport com.vaadin.flow.component.orderedlayout.VerticalLayout;\nimport com.vaadin.flow.router.Route;\nimport java.util.concurrent.CompletableFuture;\n\n@Route(value = \"report\", layout = MainLayout.class)\npublic class ReportView extends VerticalLayout {\n\n    public ReportView() {\n        Span status = new Span(\"Idle\");\n        Button run = new Button(\"Run report\", e -&gt; {\n            UI ui = UI.getCurrent();                       // capture while on the UI thread\n            status.setText(\"Working...\");\n            CompletableFuture.supplyAsync(this::slowReport).thenAccept(result -&gt;\n                ui.access(() -&gt; status.setText(\"Done: \" + result)));   // safe hand-back\n        });\n        add(run, status);\n    }\n\n    private String slowReport() {\n        try { Thread.sleep(3000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); }\n        return \"42 rows\";\n    }\n}</code></pre>\n<p>Capture <code>UI.getCurrent()</code> before leaving the UI thread: on a worker thread it returns null. <code>ui.access</code> acquires the session lock and, with <code>@Push</code>, sends the change immediately. Without push, the update would wait for the next user interaction. Handle the case where the user navigated away: use <code>addDetachListener</code> to cancel the work, or the callback will write to a component that is gone, which is harmless but wasteful. The full treatment, with broadcasters and cleanup, is in <a href=\"/library/vaadin-push-use-server-updates\">server push</a>.</p>\n<h2>Security</h2>\n<p>Because the client is generic and listeners run on the server, security is the same as for any Spring application with one important addition: views are reachable by URL. Secure the routes and the services.</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/AdminView.java\"><code class=\"language-java\">import com.vaadin.flow.component.orderedlayout.VerticalLayout;\nimport com.vaadin.flow.router.Route;\nimport jakarta.annotation.security.RolesAllowed;\n\n@Route(value = \"admin\", layout = MainLayout.class)\n@RolesAllowed(\"ADMIN\")\npublic class AdminView extends VerticalLayout {\n}</code></pre>\n<p>Vaadin integrates with Spring Security through <code>VaadinWebSecurity</code>, which wires login view handling and checks <code>@RolesAllowed</code>, <code>@PermitAll</code> and <code>@AnonymousAllowed</code> on views. Two rules cover most mistakes. First, hiding a menu item is not security; the route must be protected. Second, check authorization in the service layer too (<code>@PreAuthorize</code>), because a view is only one caller. The setup, a login view, role-based menus and CSRF behavior are in <a href=\"/library/vaadin-spring-security-secure-app\">securing a Vaadin app with Spring Security</a>.</p>\n<h2>Test without a browser</h2>\n<p>Because the UI is Java objects, most of it can be tested as Java. The form rules are the best place to start, since <code>Binder</code> runs without a browser or a server. This test builds the same binder the editor uses and checks that an invalid bean is rejected and a valid one is written:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/crm/ui/CustomerBinderTest.java\"><code class=\"language-java\">import static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertFalse;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\nimport com.vaadin.flow.component.textfield.EmailField;\nimport com.vaadin.flow.component.textfield.TextField;\nimport com.vaadin.flow.data.binder.BeanValidationBinder;\nimport org.junit.jupiter.api.Test;\n\nclass CustomerBinderTest {\n\n    private final BeanValidationBinder&lt;Customer&gt; binder = new BeanValidationBinder&lt;&gt;(Customer.class);\n    private final TextField name = new TextField();\n    private final EmailField email = new EmailField();\n\n    CustomerBinderTest() {\n        binder.forField(name).asRequired(\"Name is required\").bind(\"name\");\n        binder.forField(email).asRequired(\"Email is required\").bind(\"email\");\n    }\n\n    @Test\n    void rejectsBadEmail() {\n        name.setValue(\"Ada\");\n        email.setValue(\"not-an-email\");\n        assertFalse(binder.writeBeanIfValid(new Customer()));\n    }\n\n    @Test\n    void writesValidValues() {\n        name.setValue(\"Ada\");\n        email.setValue(\"ada@example.com\");\n        Customer c = new Customer();\n        assertTrue(binder.writeBeanIfValid(c));\n        assertEquals(\"ada@example.com\", c.getEmail());\n    }\n}</code></pre>\n<p>Vaadin also ships browserless testing support that creates a UI in the JVM so a test can find components, type into fields and click buttons, and the Karibu-Testing library does the same for views. Use them for view logic such as \"Save closes the dialog and refreshes the grid\". Cover three layers: service tests for business rules, browserless tests for view behavior, and a handful of end-to-end browser tests against the built production jar, which is where problems that only appear with the compiled frontend are found.</p>\n<h2>Memory: sessions live on the server</h2>\n<p>The state of every open browser tab sits in the JVM: the component tree, the grid's currently cached rows, the binder, the beans you hold. Memory scales with active users and the size of each UI. Three habits keep it in check:</p>\n<ul><li><strong>Keep data in the database, not in views.</strong> A view that loads 50,000 customers into a list holds them for the life of the tab. Use the lazy callback.</li><li><strong>Hold ids, not object graphs.</strong> Re-fetch on demand.</li><li><strong>Set the session timeout deliberately</strong> and size the heap for concurrent users: if each active UI costs 1 to 3 MB, a thousand concurrent users need 1 to 3 GB for sessions alone, before caches. Measure with a heap dump of a loaded test instance.</li></ul>\n<p>The monitoring and sizing approach is in <a href=\"/library/vaadin-session-memory-handle-sessions-apps\">session memory</a>, and the same server-side-state trade-off explains why sticky sessions matter behind a load balancer. For the underlying JVM view of the numbers, see JVM memory areas.</p>\n<h2>Ship the production build</h2>\n<p>Development mode compiles the frontend on demand and ships tooling; it must not reach production. The production build bundles and minifies the frontend into the jar. Build with the profile defined above:</p>\n<pre><code class=\"language-bash\">./mvnw -Pproduction clean package\njava -jar target/crm-1.0.jar</code></pre>\n<p>A blank white page after deployment is nearly always this step skipped: the app started in development mode in a container with no Node, or the profile never ran. The checklist is in <a href=\"/library/vaadin-production-build-blank-page-fix\">fixing a blank page after a production build</a>, and the bundle options (offline use, CI caching of <code>node_modules</code>, the <code>frontend/generated</code> directory) are in <a href=\"/library/vaadin-production-build-bundle-deploy\">the production bundle</a>. Add three production practices: set <code>vaadin.productionMode=true</code> only through the profile and not by hand, cache the frontend dependencies in CI so builds are not 8 minutes, and test the built jar, not the dev server.</p>\n<h2>Navigation, parameters and the browser's back button</h2>\n<p>A Vaadin application is still a web application: each view has a URL, the back button works and a link can be pasted into chat. That only holds if you put state in the URL when it should be there. A detail page for one customer takes the id as a route parameter:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/crm/ui/CustomerDetailView.java\"><code class=\"language-java\">import com.vaadin.flow.component.html.H2;\nimport com.vaadin.flow.component.orderedlayout.VerticalLayout;\nimport com.vaadin.flow.router.BeforeEvent;\nimport com.vaadin.flow.router.HasUrlParameter;\nimport com.vaadin.flow.router.NotFoundException;\nimport com.vaadin.flow.router.Route;\n\n@Route(value = \"customers\", layout = MainLayout.class)\npublic class CustomerDetailView extends VerticalLayout implements HasUrlParameter&lt;Long&gt; {\n\n    private final CustomerRepository repository;\n\n    public CustomerDetailView(CustomerRepository repository) {\n        this.repository = repository;\n    }\n\n    @Override\n    public void setParameter(BeforeEvent event, Long id) {\n        Customer customer = repository.findById(id).orElseThrow(NotFoundException::new);\n        removeAll();\n        add(new H2(customer.getName()));\n    }\n}</code></pre>\n<p><code>/customers/42</code> now opens this view with <code>id = 42</code>, and a missing customer produces the router's not-found page instead of a stack trace. Query parameters work for filters: read them with <code>event.getLocation().getQueryParameters()</code> and write them back with <code>UI.getCurrent().navigate(...)</code> so a filtered grid can be bookmarked. The rule of thumb is that anything a user would want to share belongs in the URL, and anything private to the interaction (a half-typed value) stays in the component.</p>\n<p>Navigation also has guards. A <code>BeforeEnterObserver</code> can redirect (to login, to a wizard's first step) and a <code>BeforeLeaveObserver</code> can warn about unsaved changes:</p>\n<pre><code class=\"language-java\">@Override\npublic void beforeLeave(BeforeLeaveEvent event) {\n    if (binder.hasChanges()) {\n        BeforeLeaveEvent.ContinueNavigationAction action = event.postpone();\n        ConfirmDialog dialog = new ConfirmDialog(\"Discard changes?\", \"Unsaved edits will be lost.\",\n                \"Discard\", e -&gt; action.proceed());\n        dialog.setCancelable(true);\n        dialog.open();\n    }\n}</code></pre>\n<p><code>event.postpone()</code> pauses navigation and returns an action you call to continue. This is the Vaadin counterpart of the browser's \"leave site?\" prompt, and it is only needed on forms that matter.</p>\n<h2>Dialogs, notifications and confirming destructive actions</h2>\n<p>Three small components carry most of the feedback in a business UI. <code>Notification</code> is a transient message, <code>Dialog</code> is a modal container, and <code>ConfirmDialog</code> is a ready-made question with buttons. Use a confirmation before anything destructive, and use a notification for everything else; a dialog for \"Saved!\" trains users to dismiss dialogs without reading them.</p>\n<p>Deleting a customer from the grid's context shows the pattern:</p>\n<pre><code class=\"language-java\">private void confirmDelete(Customer customer) {\n    ConfirmDialog dialog = new ConfirmDialog();\n    dialog.setHeader(\"Delete \" + customer.getName() + \"?\");\n    dialog.setText(\"This cannot be undone.\");\n    dialog.setCancelable(true);\n    dialog.setConfirmText(\"Delete\");\n    dialog.setConfirmButtonTheme(\"error primary\");\n    dialog.addConfirmListener(e -&gt; {\n        service.delete(customer);\n        grid.getDataProvider().refreshAll();\n        Notification.show(\"Deleted \" + customer.getName(), 3000, Notification.Position.BOTTOM_START);\n    });\n    dialog.open();\n}</code></pre>\n<p>Tell the user what was affected in the confirmation text, and let the notification expire on its own after a few seconds. For errors, show the reason and the next step, never a bare \"Error\". Unexpected exceptions in a listener reach Vaadin's error handler, which logs them and shows a generic message; replace it with your own to add a correlation id:</p>\n<pre><code class=\"language-java\">VaadinSession.getCurrent().setErrorHandler(event -&gt; {\n    String id = java.util.UUID.randomUUID().toString().substring(0, 8);\n    log.error(\"UI error {}\", id, event.getThrowable());\n    Notification.show(\"Something went wrong. Reference \" + id);\n});</code></pre>\n<p>Support can then find the stack trace from the reference a user reads out.</p>\n<h2>Building bigger screens from smaller components</h2>\n<p>A view that grows past two hundred lines is a class that mixes layout, data access and behavior. Vaadin makes extraction easy because a component is just a class that extends a layout. Pull the filter bar out of the list view:</p>\n<pre><code class=\"language-java\">public class CustomerFilterBar extends HorizontalLayout {\n\n    private final TextField text = new TextField();\n\n    public CustomerFilterBar(Runnable onChange) {\n        text.setPlaceholder(\"Filter by name\");\n        text.setValueChangeMode(ValueChangeMode.LAZY);\n        text.addValueChangeListener(e -&gt; onChange.run());\n        add(text);\n    }\n\n    public String value() { return text.getValue(); }\n}</code></pre>\n<p>The view passes a callback and reads <code>value()</code>, and the bar can be reused and tested on its own. Three conventions keep a Vaadin codebase tidy as it grows:</p>\n<ol><li>**A component receives what it needs in its constructor and reports events through callbacks or <code>ComponentEvent</code>s.** It does not reach into its parent.</li><li><strong>Data access happens in a presenter or service, not in components.</strong> A component that calls a repository is untestable without a database.</li><li><strong>Name views for the task, not the entity.</strong> <code>CustomerImportView</code> and <code>CustomerListView</code> can coexist; a <code>CustomerView</code> that does everything cannot be split later.</li></ol>\n<p>For a widget that has no counterpart in the library, writing a custom component covers wrapping a web component, and a full CRUD application strings these ideas together on a real schema.</p>\n<h2>Internationalization</h2>\n<p>If your users read more than one language, build it in from the first view, because retrofitting is a search through every string literal. Vaadin provides <code>I18NProvider</code>, and <code>getTranslation</code> looks up a key for the current locale:</p>\n<pre><code class=\"language-java\">@Component\npublic class Messages implements I18NProvider {\n\n    @Override\n    public List&lt;Locale&gt; getProvidedLocales() {\n        return List.of(Locale.ENGLISH, Locale.GERMAN);\n    }\n\n    @Override\n    public String getTranslation(String key, Locale locale, Object... params) {\n        ResourceBundle bundle = ResourceBundle.getBundle(\"messages\", locale);\n        String value = bundle.containsKey(key) ? bundle.getString(key) : \"!\" + key;\n        return params.length == 0 ? value : MessageFormat.format(value, params);\n    }\n}</code></pre>\n<p>Views then call <code>getTranslation(\"customer.save\")</code> instead of writing \"Save\". The <code>!key</code> fallback makes a missing translation visible during testing instead of throwing. Dates and numbers should go through the locale as well: <code>DatePicker</code> and <code>NumberField</code> respect <code>UI.getLocale()</code>.</p>\n<h2>Performance: what is actually slow</h2>\n<p>Vaadin applications feel slow for four reasons, in this order of likelihood.</p>\n<p><strong>A listener does slow work on the UI thread.</strong> The session is locked while a listener runs, so a six second report query freezes that user's UI, including other tabs in the session. Move it off-thread with <code>CompletableFuture</code> and <code>ui.access</code> as in the push section, and show a progress indicator in the meantime.</p>\n<p><strong>A grid loads too much.</strong> An unbounded <code>findAll()</code> fed to <code>setItems(list)</code> loads the whole table into memory and serializes much of it to the client. Use the lazy callback, and make sure the query is indexed for the sort columns the user can click. A sortable column the database cannot sort quickly is a performance bug waiting for a click.</p>\n<p><strong>Too many components.</strong> A page with thousands of live components, such as a loop that creates a row of fields per record, is slow to build and slow to synchronize. Use a <code>Grid</code> with renderers, or a virtual list.</p>\n<p><strong>The network is far from the server.</strong> Every interaction is a round trip, so a user across an ocean from the server feels each one. Reduce chatty interactions: handle <code>ValueChangeMode.ON_BLUR</code> instead of <code>EAGER</code> for fields that do not need instant feedback, and avoid listeners on high-frequency events such as <code>scroll</code>.</p>\n<p>Measure before changing. The browser's network panel shows the size and count of the <code>UIDL</code> requests, and a profiler or thread dumps on the server show what a slow listener is doing.</p>\n<h2>Containers and deployment</h2>\n<p>A Vaadin production build is an ordinary Spring Boot jar, so it containerizes like any other service. The two details specific to Vaadin are that the build runs the frontend compiler, which needs Node (the plugin downloads one, and the CI cache should hold it), and that sessions are stateful. Behind a load balancer, either use sticky sessions or store sessions in a shared store; without one of them, a user's next request lands on an instance that never saw their UI and receives a session-expired page.</p>\n<pre><code class=\"language-dockerfile\">FROM eclipse-temurin:25-jdk AS build\nWORKDIR /src\nCOPY . .\nRUN ./mvnw -q -Pproduction -DskipTests package\n\nFROM eclipse-temurin:25-jre\nCOPY --from=build /src/target/crm-1.0.jar /app/crm.jar\nENV JAVA_TOOL_OPTIONS=\"-XX:MaxRAMPercentage=75\"\nENTRYPOINT [\"java\", \"-jar\", \"/app/crm.jar\"]</code></pre>\n<p>The build-stage layout is explained in <a href=\"/library/docker-multi-stage-java-use-builds\">multi-stage Docker builds</a>. Expose a health endpoint through Spring Boot Actuator for the readiness probe, because a Vaadin app that is still compiling its bundle in a misbuilt image answers requests with errors long before a plain TCP check notices.</p>\n<h2>Upgrading between versions</h2>\n<p>Vaadin releases a major version about once a year and keeps the previous one supported. Upgrades are mostly mechanical, but plan for them:</p>\n<ol><li>Read the release notes and the migration guide for each major before changing the version number.</li><li>Upgrade the BOM version in one place, then compile; deprecated methods turn into errors one major later, so fix deprecations when they appear.</li><li>Delete <code>node_modules</code>, <code>package-lock.json</code> and the generated frontend folder, then rebuild, since stale generated files are the most common cause of strange errors after an upgrade.</li><li>Run the browserless and end-to-end tests before you look at the UI.</li></ol>\n<h2>Common mistakes</h2>\n<table><thead><tr><th>Mistake</th><th>What happens</th><th>Fix</th></tr></thead><tbody><tr><td>Storing shared data in a view's fields</td><td>Each navigation creates a new view, so the data disappears or is per-user</td><td>Put shared data in a service or a Spring bean with the right scope</td></tr><tr><td>Calling <code>UI.getCurrent()</code> in a background thread</td><td>Returns <code>null</code> and a <code>NullPointerException</code></td><td>Capture the UI before leaving the UI thread</td></tr><tr><td><code>grid.setItems(repository.findAll())</code> on a big table</td><td>Slow page and heavy session memory</td><td>Use the lazy <code>setItems(query -&gt; ...)</code> overload</td></tr><tr><td>Hiding a menu item as the only access control</td><td>The route is still reachable by URL</td><td>Annotate the view and the service</td></tr><tr><td>Running the dev build in production</td><td>Blank page or slow first load</td><td>Build with the <code>production</code> profile</td></tr><tr><td>Creating components in a loop per record</td><td>Thousands of live components</td><td>Use a <code>Grid</code> with a component renderer for the few rows that need one</td></tr><tr><td>Ignoring session timeouts in testing</td><td>Users report sudden \"session expired\"</td><td>Test with a short timeout and a handler that explains it</td></tr></tbody></table>\n<h2>When Vaadin is the wrong choice</h2>\n<p>Vaadin earns its place in applications that look like software: forms, tables, workflows, dashboards, used by a known group of people, written by a Java team. It is a poor fit for:</p>\n<ul><li><strong>Public, content-heavy sites that need to rank in search.</strong> Server-rendered pages and static generation do this better.</li><li><strong>Highly custom, animation-driven or offline-first interfaces.</strong> You will fight the generic client.</li><li><strong>Teams with strong frontend skills and a mobile app to share an API with.</strong> A typed REST or GraphQL API serves both, see <a href=\"/library/rest-api-design-rules-java-teams\">REST design for Java teams</a> for how to do it well.</li><li><strong>Very large numbers of concurrent anonymous users.</strong> Per-session server memory is the cost.</li></ul>\n<p>A middle option for teams that want server-rendered pages with small interactive pieces is a template engine plus HTMX, compared in Vaadin against HTMX and Thymeleaf. For a bigger application that persists data, the next step is a CRUD application with JPA, and when a component you need does not exist, write your own.</p>\n<h2>A short checklist before you call it done</h2>\n<ol><li>Services own transactions and authorization; views call services.</li><li>Every route has an access annotation, and sensitive services check roles too.</li><li>Large grids use the lazy callback with a bounded page size.</li><li>Long operations run off the UI thread and return through <code>ui.access</code>.</li><li>Memory per session is measured under load.</li><li>The built jar, with the production profile, is what CI tests and deploys.</li><li>Version upgrades read the release notes: component APIs change between majors.</li></ol>\n<p>The entry point for everything else is the <a href=\"https://vaadin.com/docs\">Vaadin documentation</a>, and the data binding reference is <a href=\"https://vaadin.com/docs/latest/flow/binding-data\">binding data to forms</a>.</p>","date_published":"2026-11-14T04:19:31+00:00","tags":["Vaadin"]},{"id":"https://javahacks.dev/library/jsf-primefaces-guide-javaserver-faces-explained","url":"https://javahacks.dev/library/jsf-primefaces-guide-javaserver-faces-explained","title":"JSF PrimeFaces Guide to Maintaining JavaServer Faces Apps","summary":"Understand the Faces lifecycle, scopes, expression language and PrimeFaces components well enough to maintain and extend an existing application.","content_html":"<p>The <a href=\"https://jakarta.ee/specifications/faces/\">Jakarta Faces specification</a> and the <a href=\"https://www.primefaces.org/showcase/\">PrimeFaces showcase</a> are the primary sources here. There are a lot of JavaServer Faces applications still in production, many of them in banks, insurers and governments, and many of them maintained by people who inherited them. The framework behaves strangely until the lifecycle is clear, and then it behaves exactly as documented. This guide explains Jakarta Faces 4 and PrimeFaces well enough to maintain an application and to find the cause of the next odd error. The examples run on Jakarta EE 10 or newer with PrimeFaces on a recent servlet container.</p>\n<p>If you are starting from zero, the <a href=\"/library/jsf-tutorial-javaserver-faces-beginners\">JavaServer Faces tutorial for beginners</a> builds a first page. For the platform around Faces, see <a href=\"/library/jakarta-ee-replaced-java\">what Jakarta EE is</a>.</p>\n<h2>The lifecycle explains most bugs</h2>\n<p>Every Faces request passes through up to six phases:</p>\n<table><thead><tr><th>Phase</th><th>What happens</th><th>What breaks here</th></tr></thead><tbody><tr><td>Restore view</td><td>The component tree is rebuilt or created</td><td><code>ViewExpiredException</code></td></tr><tr><td>Apply request values</td><td>Submitted values are copied onto components</td><td>Nothing, usually</td></tr><tr><td>Process validations</td><td>Converters and validators run</td><td>Validation errors skip to render</td></tr><tr><td>Update model values</td><td>Valid values are written into beans</td><td>Null in the expression path</td></tr><tr><td>Invoke application</td><td>Your action method runs</td><td>Never reached if validation failed</td></tr><tr><td>Render response</td><td>The page is produced</td><td>Anything bound to a bad property</td></tr></tbody></table>\n<p>The classic puzzle, a button that does nothing, is a validation failure in phase three. The request jumps to render response, the action method never runs, and the only evidence is a message the page may not display. Add <code>&lt;h:messages /&gt;</code> or <code>&lt;p:messages /&gt;</code> during development and the page tells you. A fuller walk through is in <a href=\"/library/jsf-lifecycle-phases-explained\">JSF lifecycle phases explained</a>.</p>\n<h2>Beans: use CDI</h2>\n<pre data-filename=\"src/main/java/dev/javahacks/web/CustomerBean.java\"><code class=\"language-java\">@Named\n@ViewScoped\npublic class CustomerBean implements Serializable {\n\n    @Inject\n    private CustomerService service;\n\n    private String filter;\n    private List&lt;Customer&gt; customers;\n\n    @PostConstruct\n    void init() {\n        customers = service.findAll();\n    }\n\n    public void search() {\n        customers = service.search(filter);\n    }\n\n    public String getFilter() { return filter; }\n    public void setFilter(String filter) { this.filter = filter; }\n    public List&lt;Customer&gt; getCustomers() { return customers; }\n}</code></pre>\n<p><code>@Named</code> makes the bean visible to expressions, and <code>@ViewScoped</code> (from <code>jakarta.faces.view</code>) keeps it alive while the user remains on the same view, then discards it. The bean must be <code>Serializable</code>, because the container may passivate it. The legacy <code>@ManagedBean</code> was deprecated in Faces 2.3 and removed in Faces 4.0, so a migration from old code starts here. Compare the two models in <a href=\"/library/jsf-managed-bean-vs-cdi-beans\">managed beans vs CDI beans</a>.</p>\n<h2>Scopes decide how long state lives</h2>\n<table><thead><tr><th>Scope</th><th>Lives for</th><th>Use it for</th></tr></thead><tbody><tr><td><code>@RequestScoped</code></td><td>One request</td><td>Read-only pages, simple actions</td></tr><tr><td><code>@ViewScoped</code></td><td>One view, across AJAX calls</td><td>Forms and tables</td></tr><tr><td><code>@SessionScoped</code></td><td>The user session</td><td>Login identity, preferences</td></tr><tr><td><code>@ApplicationScoped</code></td><td>The application</td><td>Lookups shared by everyone</td></tr></tbody></table>\n<p>Putting form state in session scope is the most common mistake: two browser tabs overwrite each other. Use view scope for forms. <a href=\"/library/jsf-bean-scopes-explained-examples\">JSF bean scopes with examples</a> shows the failure for each.</p>\n<h2>Facelets and expression language</h2>\n<pre data-filename=\"src/main/webapp/customers.xhtml\"><code class=\"language-xml\">&lt;!DOCTYPE html&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"\n      xmlns:h=\"jakarta.faces.html\"\n      xmlns:f=\"jakarta.faces.core\"\n      xmlns:p=\"http://primefaces.org/ui\"&gt;\n&lt;h:head&gt;&lt;title&gt;Customers&lt;/title&gt;&lt;/h:head&gt;\n&lt;h:body&gt;\n    &lt;h:form id=\"search\"&gt;\n        &lt;p:inputText id=\"filter\" value=\"#{customerBean.filter}\" /&gt;\n        &lt;p:commandButton value=\"Search\" action=\"#{customerBean.search}\"\n                         process=\"@form\" update=\":results\" /&gt;\n    &lt;/h:form&gt;\n\n    &lt;p:dataTable id=\"results\" value=\"#{customerBean.customers}\" var=\"c\"&gt;\n        &lt;p:column headerText=\"Name\"&gt;&lt;h:outputText value=\"#{c.name}\" /&gt;&lt;/p:column&gt;\n        &lt;p:column headerText=\"Email\"&gt;&lt;h:outputText value=\"#{c.email}\" /&gt;&lt;/p:column&gt;\n    &lt;/p:dataTable&gt;\n&lt;/h:body&gt;\n&lt;/html&gt;</code></pre>\n<p>The namespaces <code>jakarta.faces.html</code> and <code>jakarta.faces.core</code> are the Faces 4 form; Faces 3 and older used <code>http://xmlns.jcp.org/jsf/html</code> and <code>/core</code>. An application that mixes them fails to render components. The expression <code>#{customerBean.filter}</code> is a value binding: reading calls <code>getFilter()</code>, submitting calls <code>setFilter()</code>. If the path hits a null, you get <a href=\"/library/target-unreachable-identifier-resolved-null-fix\">Target Unreachable, identifier resolved to null</a>. Read <a href=\"/library/jsf-expression-language-value-binding\">expression language and value binding</a> for the resolution rules.</p>\n<h2>PrimeFaces: process and update</h2>\n<p>The two attributes you will use most are <code>process</code>, which names the components whose values are submitted and validated, and <code>update</code>, which names the components re-rendered afterwards. A button that fixes everything with <code>update=\"@all\"</code> works and wastes bandwidth, and a button missing from <code>process</code> leaves a field unsubmitted. Reference by client id: <code>:results</code> with a leading colon means \"from the root\", which is needed when the target sits outside the current form.</p>\n<h2>Why a view expires</h2>\n<p>Faces stores view state in the session (the default) or in the client. When the session expires or the server restarts, the next postback cannot find its view and throws [<code>ViewExpiredException</code>](/library/viewexpiredexception-fix-javaserver-faces). Handle it with an error page that redirects to the login or the view, and consider whether a long form needs a longer session or a client-side state setting.</p>\n<h2>Finding a component: the id rules that cost everyone an afternoon</h2>\n<p>The <code>update</code> and <code>process</code> attributes take search expressions, and most \"it did not refresh\" bugs are a wrong expression. Faces gives each naming container (a <code>h:form</code>, a <code>p:dataTable</code>, a composite component) its own id scope, and the client id joins the ids with a colon. A field <code>filter</code> inside the form <code>search</code> has the client id <code>search:filter</code>. The rules in practice:</p>\n<table><thead><tr><th>Expression</th><th>Meaning</th></tr></thead><tbody><tr><td><code>@this</code></td><td>The component that fired the event</td></tr><tr><td><code>@form</code></td><td>The enclosing form</td></tr><tr><td><code>@parent</code></td><td>The parent component</td></tr><tr><td><code>@namingcontainer</code></td><td>The closest enclosing naming container</td></tr><tr><td><code>@all</code></td><td>The whole page</td></tr><tr><td><code>results</code></td><td>A sibling or descendant id, found relative to the current naming container</td></tr><tr><td><code>:results</code></td><td>A component found from the view root, even across forms</td></tr><tr><td><code>:search:filter</code></td><td>An absolute client id</td></tr></tbody></table>\n<p>A button inside the form <code>search</code> that updates a table outside the form must use <code>:results</code>, since a bare <code>results</code> is looked up inside <code>search</code> and fails with \"Cannot find component with identifier\". When in doubt, open the browser's developer tools, read the rendered <code>id</code> attribute and use it with a leading colon. The separator is configurable (<code>jakarta.faces.SEPARATOR_CHAR</code>), and changing it breaks every CSS selector and every piece of JavaScript that hard-coded the colon, so leave it alone.</p>\n<p>Use <code>process</code> narrowly. A button that does not need the whole form, such as \"cancel\", should not submit and validate it:</p>\n<pre><code class=\"language-xml\">&lt;p:commandButton value=\"Cancel\" action=\"#{customerBean.cancel}\"\n                 process=\"@this\" update=\":messages\" immediate=\"true\" /&gt;</code></pre>\n<p><code>immediate=\"true\"</code> moves the action ahead of validation, so a cancel button does not fail because a required field is empty. Pair it with <code>process=\"@this\"</code> or <code>immediate</code> alone can still leave you with surprising values.</p>\n<h2>A form with validation and conversion</h2>\n<p>Validation is where Faces earns its keep and where most maintenance questions start. Bean Validation annotations on the model are enforced by Faces in phase three, and messages come back to the page:</p>\n<pre><code class=\"language-java\">public class CustomerForm implements Serializable {\n\n    @NotBlank(message = \"Name is required\")\n    @Size(max = 80)\n    private String name;\n\n    @Email(message = \"Enter a valid email address\")\n    private String email;\n\n    @Min(value = 0, message = \"Credit must not be negative\")\n    private BigDecimal creditLimit;\n\n    // getters and setters\n}</code></pre>\n<pre><code class=\"language-xml\">&lt;h:form id=\"edit\"&gt;\n    &lt;p:messages id=\"messages\" showDetail=\"true\" closable=\"true\" /&gt;\n\n    &lt;p:outputLabel for=\"name\" value=\"Name\" /&gt;\n    &lt;p:inputText id=\"name\" value=\"#{customerBean.form.name}\" required=\"true\" /&gt;\n\n    &lt;p:outputLabel for=\"email\" value=\"Email\" /&gt;\n    &lt;p:inputText id=\"email\" value=\"#{customerBean.form.email}\" /&gt;\n\n    &lt;p:outputLabel for=\"credit\" value=\"Credit limit\" /&gt;\n    &lt;p:inputNumber id=\"credit\" value=\"#{customerBean.form.creditLimit}\" decimalPlaces=\"2\" /&gt;\n\n    &lt;p:commandButton value=\"Save\" action=\"#{customerBean.save}\"\n                     process=\"@form\" update=\"@form\" /&gt;\n&lt;/h:form&gt;</code></pre>\n<p>A custom rule that spans no single annotation becomes a validator. It receives the submitted value and throws a <code>ValidatorException</code> with a message:</p>\n<pre><code class=\"language-java\">@FacesValidator(\"uniqueEmail\")\npublic class UniqueEmailValidator implements Validator&lt;String&gt; {\n\n    @Inject\n    private CustomerService customers;\n\n    @Override\n    public void validate(FacesContext context, UIComponent component, String value) {\n        if (value != null &amp;&amp; customers.emailExists(value)) {\n            throw new ValidatorException(new FacesMessage(\n                FacesMessage.SEVERITY_ERROR, \"That email is already registered\", null));\n        }\n    }\n}</code></pre>\n<p>Injection into a <code>@FacesValidator</code> works in Faces 4 on a CDI-enabled runtime, and fails with a <code>NullPointerException</code> on older setups where the validator is not a managed bean. If you see that, add <code>managed=\"true\"</code> to the annotation, which is available from Faces 2.3, or register it as a CDI bean. A converter follows the same pattern and is needed whenever a component holds an object and the page holds a string, which is typical for a drop-down of entities:</p>\n<pre><code class=\"language-java\">@FacesConverter(forClass = Country.class, managed = true)\npublic class CountryConverter implements Converter&lt;Country&gt; {\n\n    @Inject\n    private CountryRepository countries;\n\n    @Override\n    public Country getAsObject(FacesContext context, UIComponent component, String value) {\n        return value == null || value.isBlank() ? null : countries.findByCode(value);\n    }\n\n    @Override\n    public String getAsString(FacesContext context, UIComponent component, Country value) {\n        return value == null ? \"\" : value.getCode();\n    }\n}</code></pre>\n<p>A \"Validation Error: Value is not valid\" on a select menu almost always means the converter or <code>equals</code> method of the entity is wrong, because Faces compares the submitted object with the available options before it accepts it.</p>\n<h2>A large table without loading it all: lazy data</h2>\n<p><code>p:dataTable</code> with a plain list loads every row into the view. For anything over a few hundred rows, a lazy model asks your service for one page at a time and passes sorting and filtering through:</p>\n<pre><code class=\"language-java\">public class CustomerLazyModel extends LazyDataModel&lt;Customer&gt; {\n\n    private final CustomerService service;\n\n    public CustomerLazyModel(CustomerService service) {\n        this.service = service;\n    }\n\n    @Override\n    public int count(Map&lt;String, FilterMeta&gt; filterBy) {\n        return (int) service.count(toCriteria(filterBy));\n    }\n\n    @Override\n    public List&lt;Customer&gt; load(int first, int pageSize,\n                               Map&lt;String, SortMeta&gt; sortBy, Map&lt;String, FilterMeta&gt; filterBy) {\n        return service.page(toCriteria(filterBy), toOrder(sortBy), first, pageSize);\n    }\n\n    @Override\n    public String getRowKey(Customer customer) {\n        return String.valueOf(customer.getId());\n    }\n\n    @Override\n    public Customer getRowData(String rowKey) {\n        return service.find(Long.valueOf(rowKey));\n    }\n}</code></pre>\n<pre><code class=\"language-xml\">&lt;p:dataTable id=\"results\" value=\"#{customerBean.model}\" var=\"c\" lazy=\"true\"\n             paginator=\"true\" rows=\"25\" rowKey=\"#{c.id}\" selectionMode=\"single\"\n             selection=\"#{customerBean.selected}\"&gt;\n    &lt;p:column headerText=\"Name\" sortBy=\"#{c.name}\" filterBy=\"#{c.name}\"&gt;\n        &lt;h:outputText value=\"#{c.name}\" /&gt;\n    &lt;/p:column&gt;\n&lt;/p:dataTable&gt;</code></pre>\n<p>Method signatures on <code>LazyDataModel</code> changed between PrimeFaces major versions, so match them to the version you run. The translation from <code>FilterMeta</code> and <code>SortMeta</code> to a query is the part to write carefully: build the <code>where</code> clause from an allow-list of column names, since the field names come from the browser, which is the same injection risk as in any other API.</p>\n<h2>Navigation: post, redirect, get</h2>\n<p>A button that returns a string navigates, and without a redirect the browser's address bar stays on the old URL and a refresh resubmits the form. Ask for a redirect and pass the data in the URL or the flash:</p>\n<pre><code class=\"language-java\">public String save() {\n    Customer saved = service.save(form.toCustomer());\n    FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);\n    FacesContext.getCurrentInstance().addMessage(null,\n        new FacesMessage(FacesMessage.SEVERITY_INFO, \"Saved \" + saved.getName(), null));\n    return \"customer?faces-redirect=true&amp;id=\" + saved.getId();\n}</code></pre>\n<p>The target page reads the id as a view parameter and loads the data with a view action, which runs in the invoke application phase, after the parameter has been converted and validated:</p>\n<pre><code class=\"language-xml\">&lt;f:metadata&gt;\n    &lt;f:viewParam name=\"id\" value=\"#{customerView.id}\" required=\"true\" /&gt;\n    &lt;f:viewAction action=\"#{customerView.load}\" /&gt;\n&lt;/f:metadata&gt;</code></pre>\n<p>This gives you bookmarkable URLs, which plain Faces navigation does not. The <code>setKeepMessages(true)</code> line carries the \"Saved\" message across the redirect, and without it the message is lost. Keep identifiers, not whole objects, in the URL, and load the object again on the other side.</p>\n<h2>Templates and composite components</h2>\n<p>Repeating the page chrome in every file is the first thing to remove from a growing application. A template defines the frame, and each page fills in the holes:</p>\n<pre><code class=\"language-xml\">&lt;!-- WEB-INF/templates/layout.xhtml --&gt;\n&lt;ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n                xmlns:ui=\"jakarta.faces.facelets\"\n                xmlns:h=\"jakarta.faces.html\"&gt;\n    &lt;h:head&gt;&lt;title&gt;&lt;ui:insert name=\"title\"&gt;Shop&lt;/ui:insert&gt;&lt;/title&gt;&lt;/h:head&gt;\n    &lt;h:body&gt;\n        &lt;ui:include src=\"/WEB-INF/templates/menu.xhtml\" /&gt;\n        &lt;ui:insert name=\"content\" /&gt;\n    &lt;/h:body&gt;\n&lt;/ui:composition&gt;</code></pre>\n<pre><code class=\"language-xml\">&lt;!-- customers.xhtml --&gt;\n&lt;ui:composition template=\"/WEB-INF/templates/layout.xhtml\"\n                xmlns:ui=\"jakarta.faces.facelets\"\n                xmlns:h=\"jakarta.faces.html\"&gt;\n    &lt;ui:define name=\"title\"&gt;Customers&lt;/ui:define&gt;\n    &lt;ui:define name=\"content\"&gt;\n        &lt;h:outputText value=\"Customer list goes here\" /&gt;\n    &lt;/ui:define&gt;\n&lt;/ui:composition&gt;</code></pre>\n<p>Templates under <code>WEB-INF</code> cannot be requested directly by a browser. For repeated fragments with their own parameters, such as a labelled input with its message, a composite component keeps the markup in one file and exposes attributes. A good test of whether to extract one is whether three pages carry the same twenty lines.</p>\n<h2>See the lifecycle with a phase listener</h2>\n<p>When a page misbehaves and the explanations are not enough, log the phases. A <code>PhaseListener</code> prints each phase boundary and any queued messages, and shows exactly where a request stopped:</p>\n<pre><code class=\"language-java\">public class TracingPhaseListener implements PhaseListener {\n\n    private static final Logger log = Logger.getLogger(TracingPhaseListener.class.getName());\n\n    @Override\n    public void beforePhase(PhaseEvent event) {\n        log.fine(() -&gt; \"BEFORE \" + event.getPhaseId());\n    }\n\n    @Override\n    public void afterPhase(PhaseEvent event) {\n        FacesContext context = event.getFacesContext();\n        log.fine(() -&gt; \"AFTER  \" + event.getPhaseId()\n            + \" messages=\" + context.getMessageList().size()\n            + \" renderResponse=\" + context.getRenderResponse());\n    }\n\n    @Override\n    public PhaseId getPhaseId() {\n        return PhaseId.ANY_PHASE;\n    }\n}</code></pre>\n<pre><code class=\"language-xml\">&lt;!-- WEB-INF/faces-config.xml --&gt;\n&lt;faces-config xmlns=\"https://jakarta.ee/xml/ns/jakartaee\" version=\"4.0\"&gt;\n    &lt;lifecycle&gt;\n        &lt;phase-listener&gt;dev.javahacks.web.TracingPhaseListener&lt;/phase-listener&gt;\n    &lt;/lifecycle&gt;\n&lt;/faces-config&gt;</code></pre>\n<p>A request that shows <code>AFTER PROCESS_VALIDATIONS messages=1 renderResponse=true</code> and then jumps to <code>RENDER_RESPONSE</code> is a validation failure, and the message list says why. Set the project stage to <code>Development</code> while debugging so that Faces prints more detail on the page, and to <code>Production</code> for deployment, which enables caching of the compiled view.</p>\n<pre><code class=\"language-xml\">&lt;context-param&gt;\n    &lt;param-name&gt;jakarta.faces.PROJECT_STAGE&lt;/param-name&gt;\n    &lt;param-value&gt;Production&lt;/param-value&gt;\n&lt;/context-param&gt;</code></pre>\n<h2>Session timeouts and view expiry, handled on purpose</h2>\n<p>The <code>ViewExpiredException</code> section earlier said what happens. A page that handles it gracefully takes three settings. A session timeout, an error page and a decision about where view state lives:</p>\n<pre><code class=\"language-xml\">&lt;session-config&gt;\n    &lt;session-timeout&gt;30&lt;/session-timeout&gt;\n&lt;/session-config&gt;\n\n&lt;error-page&gt;\n    &lt;exception-type&gt;jakarta.faces.application.ViewExpiredException&lt;/exception-type&gt;\n    &lt;location&gt;/expired.xhtml?faces-redirect=true&lt;/location&gt;\n&lt;/error-page&gt;\n\n&lt;context-param&gt;\n    &lt;param-name&gt;jakarta.faces.STATE_SAVING_METHOD&lt;/param-name&gt;\n    &lt;param-value&gt;server&lt;/param-value&gt;\n&lt;/context-param&gt;</code></pre>\n<p>Server-side state is the default and keeps the page small, with the cost of memory per view in each session. <code>jakarta.faces.NUMBER_OF_VIEWS_IN_SESSION</code> limits how many views one session keeps, which is why an old browser tab can fail after the user opened many new ones. Client-side state keeps nothing in the session and makes each request larger, which suits clusters without sticky sessions, provided the state is encrypted (Faces does this by default with a key from the container, and you should set an explicit, shared secret for a cluster so that every node can read another's state).</p>\n<h2>Upgrading to Faces 4 in a controlled order</h2>\n<p>Most maintenance work eventually becomes an upgrade, and the changes are mechanical when done in order:</p>\n<ol><li>Move the runtime first. Choose a Jakarta EE 10 server such as WildFly, Payara or Open Liberty, or a servlet container with a Faces 4 implementation (Mojarra or MyFaces).</li><li>Rename the packages: <code>javax.faces</code> becomes <code>jakarta.faces</code>, and so does every other <code>javax</code> import. The <a href=\"/library/java-ee-jakarta-ee-namespace-change\">namespace migration post</a> covers the tooling.</li><li>Replace the XML namespaces in every <code>.xhtml</code> file: <code>http://xmlns.jcp.org/jsf/html</code> becomes <code>jakarta.faces.html</code>, and the others follow. A search-and-replace across the web folder does it.</li><li>Replace <code>@ManagedBean</code> and the <code>javax.faces.bean</code> scopes with <code>@Named</code> and the CDI scopes.</li><li>Upgrade PrimeFaces to a release built for Jakarta (the artifact has a <code>jakarta</code> classifier in some versions, check yours), and adjust the component calls that changed.</li><li>Deploy to a staging server, click through every page, and read the log for deprecation warnings.</li></ol>\n<p>Do the steps in separate commits, so that a regression has one suspect. An application that can be upgraded this way also becomes easier to hand to the next maintainer, and that is the real aim of a maintenance guide.</p>\n<h2>Performance in five habits</h2>\n<p>The slowness of a Faces page is almost always on the server, in what the beans do, and not in the component tree. These habits cover most of it:</p>\n<ul><li>Load data in <code>@PostConstruct</code> or a view action, and never in a getter, since a getter can be called many times per request. A <code>getCustomers()</code> that queries the database runs once per row of a table.</li><li>Use lazy loading for any table that can grow.</li><li>Prefer <code>rendered</code> on a component to hiding it with CSS, so that nothing is sent for what the user cannot see, and avoid <code>ui:include</code> inside large <code>ui:repeat</code> loops.</li><li>Narrow <code>process</code> and <code>update</code> to the components that matter.</li><li>Keep session and view scope small: store ids and light objects, not entity graphs, because each active view is held in memory for each user.</li></ul>\n<p>Measure with the tools you have, such as the server's access log timings and a profiler on the one slow page, before you change anything. The slow part is, more often than not, one query repeated by a getter.</p>\n<h2>AJAX events on any component</h2>\n<p>Buttons are only one trigger. Any input can fire a request on an event and update part of the page, which is how dependent drop-downs and live validation are built. With the standard tag it reads like this:</p>\n<pre><code class=\"language-xml\">&lt;h:selectOneMenu id=\"country\" value=\"#{addressBean.countryCode}\"&gt;\n    &lt;f:selectItems value=\"#{addressBean.countries}\" var=\"c\"\n                   itemValue=\"#{c.code}\" itemLabel=\"#{c.name}\" /&gt;\n    &lt;f:ajax event=\"valueChange\" listener=\"#{addressBean.loadRegions}\"\n            execute=\"@this\" render=\"region\" /&gt;\n&lt;/h:selectOneMenu&gt;\n\n&lt;h:selectOneMenu id=\"region\" value=\"#{addressBean.regionCode}\"&gt;\n    &lt;f:selectItems value=\"#{addressBean.regions}\" /&gt;\n&lt;/h:selectOneMenu&gt;</code></pre>\n<p><code>execute</code> is the standard attribute's name for what PrimeFaces calls <code>process</code>, and <code>render</code> is its <code>update</code>. PrimeFaces components usually bring their own <code>p:ajax</code> with the same ideas. Two details save time. Inputs inside the updated area are re-rendered from the bean, so the bean must hold the new state, which is why view scope matters for dependent fields. And a failed validation on the field that triggered the event stops the listener from running, which looks like the AJAX call \"doing nothing\". Check the messages component first, then the network tab for a response with an error element.</p>\n<p>When a field should validate while the user types, delay the request, so that each keystroke does not send one:</p>\n<pre><code class=\"language-xml\">&lt;p:inputText id=\"email\" value=\"#{customerBean.form.email}\"&gt;\n    &lt;p:ajax event=\"keyup\" delay=\"500\" process=\"@this\" update=\"emailMessage\" /&gt;\n&lt;/p:inputText&gt;\n&lt;p:message id=\"emailMessage\" for=\"email\" /&gt;</code></pre>\n<h2>Rendering untrusted text safely</h2>\n<p>Faces escapes output by default, so <code>&lt;h:outputText value=\"#{c.name}\" /&gt;</code> shows a name containing a script tag as text. The way to lose that protection is <code>escape=\"false\"</code>, which is sometimes used to display formatted notes. Avoid it with user input, and if the content must contain markup, sanitize it when it is stored, as described in <a href=\"/library/prevent-xss-java-web-applications\">preventing XSS in Java web applications</a>. Writing an expression straight into a page with no component, as in <code>#{c.name}</code> inside plain text, is escaped as well in Facelets, while the same text inside a <code>&lt;script&gt;</code> block is not safe from a JavaScript injection, so pass data to scripts through <code>data-</code> attributes or <code>p:remoteCommand</code> instead of concatenating it into script text.</p>\n<p>Cross-site request forgery is handled for postbacks by the view state: a form submission must carry a valid <code>jakarta.faces.ViewState</code> for a view the session knows, and an attacker's page cannot supply it. Faces 4 protects navigation by <code>GET</code> with protected views, which limits a view to be reached only from another view in the same application:</p>\n<pre><code class=\"language-xml\">&lt;f:metadata&gt;\n    &lt;f:viewParam name=\"id\" value=\"#{orderView.id}\" /&gt;\n&lt;/f:metadata&gt;</code></pre>\n<pre><code class=\"language-xml\">&lt;!-- WEB-INF/web.xml, or a faces-config entry, depending on the version --&gt;\n&lt;protected-views&gt;\n    &lt;url-pattern&gt;/admin/*&lt;/url-pattern&gt;\n&lt;/protected-views&gt;</code></pre>\n<p>Any action that changes data should be a postback, not a link with a query parameter. A <code>GET</code> that deletes a record can be triggered by an image tag on another site.</p>\n<h2>Uploading a file</h2>\n<p>A <code>p:fileUpload</code> in advanced mode posts files over AJAX and calls a listener per file, which suits attachments:</p>\n<pre><code class=\"language-xml\">&lt;h:form enctype=\"multipart/form-data\"&gt;\n    &lt;p:fileUpload listener=\"#{documentBean.upload}\" mode=\"advanced\"\n                  allowTypes=\"/(\\.|\\/)(pdf|png|jpe?g)$/\" sizeLimit=\"5242880\"\n                  update=\":messages\" /&gt;\n&lt;/h:form&gt;</code></pre>\n<pre><code class=\"language-java\">public void upload(FileUploadEvent event) throws IOException {\n    UploadedFile file = event.getFile();\n    String stored = UUID.randomUUID() + \".bin\";\n    try (InputStream in = file.getInputStream()) {\n        Files.copy(in, storageDir.resolve(stored));\n    }\n    documents.save(new Document(stored, file.getFileName(), file.getContentType(), file.getSize()));\n}</code></pre>\n<p>The page restricts type and size, and the server must repeat both checks, because the browser's check is a convenience. The stored name is generated, never the user's, so a crafted filename cannot reach another directory, as covered in <a href=\"/library/path-traversal-java-prevent-file-handling\">preventing path traversal</a>.</p>\n<h2>Testing what you maintain</h2>\n<p>Faces pages are hard to test as a whole, so test at two levels. Put as much logic as you can into plain classes and services and test those with JUnit, with no container. A backing bean should be a thin layer that calls them. The bean itself can be checked with a mocked service:</p>\n<pre><code class=\"language-java\">class CustomerBeanTest {\n\n    @Test\n    void searchFiltersCustomers() {\n        CustomerService service = mock(CustomerService.class);\n        when(service.search(\"ana\")).thenReturn(List.of(new Customer(\"Ana\", \"ana@example.com\")));\n\n        CustomerBean bean = new CustomerBean(service);\n        bean.setFilter(\"ana\");\n        bean.search();\n\n        assertEquals(1, bean.getCustomers().size());\n        assertEquals(\"Ana\", bean.getCustomers().get(0).getName());\n    }\n}</code></pre>\n<p>That test needs a constructor or a package-private setter for the service, which is a small change that makes the bean testable. For the pages, run a browser test against a deployed instance with Selenium or Playwright, limited to the paths that make money: log in, search, save, and one failing validation. A short browser suite that runs on every deployment beats a long one that nobody trusts, and it is the only test that catches a wrong <code>update</code> id, because that error exists only in the rendered page.</p>\n<h2>What to read next</h2>\n<p>A good order for a maintainer who has just inherited an application: first the <a href=\"/library/jsf-lifecycle-phases-explained\">lifecycle phases</a>, then <a href=\"/library/jsf-bean-scopes-explained-examples\">bean scopes</a>, then the PrimeFaces showcase for the components the application already uses. Keep a list of the pages that break most often, since they point at a design problem in a scope or a getter, and fix the pattern, not the page.</p>\n<h2>Where Faces is the wrong tool</h2>\n<p>Faces fits form-heavy business applications maintained by a team that knows Java. It is not a good base for a public site that needs fast first paint on mobile, an API-first product or anything that wants a rich client-side experience. If you maintain one, you do not have to leave: a steady upgrade to Faces 4 on a current Jakarta EE runtime is a well-trodden path.</p>","date_published":"2026-11-14T04:18:31+00:00","tags":["JavaServer Faces"]},{"id":"https://javahacks.dev/library/hibernate-second-level-cache-use","url":"https://javahacks.dev/library/hibernate-second-level-cache-use","title":"Hibernate Second Level Cache Guide With Spring Boot","summary":"A complete guide to the Hibernate second level cache: JCache setup, entity, collection and query caches, strategies, invalidation, clustering and measuring.","content_html":"<p>A busy service asks the database the same small questions thousands of times an hour. Which country has code <code>VN</code>? What is the name of category 12? Which currency does this tenant use? Each answer is a row that changes once a month, fetched once per request, by every request, through a connection that other work is waiting for. Hibernate has a feature built for exactly this, the second level cache, and it is also one of the easiest ways to introduce a stale data bug that survives code review. This guide covers the cache from the inside out: what it stores and how, how to switch it on, how each of the four cache types works, the consistency rules, how to configure expiry, what happens across several application nodes and how to know whether it is helping. Every step has working code. The cache sits on top of the session behaviour in <a href=\"/library/hibernate-first-level-cache-flush-modes\">Hibernate's first level cache and flush modes</a>, so read that first if the persistence context is unfamiliar.</p>\n<p>The one sentence to remember: the second level cache is a copy of rows kept in your JVM, and every question about it is a question about when that copy stops matching the database.</p>\n<h2>The two levels</h2>\n<p>Every Hibernate <code>Session</code> has a first level cache, the persistence context. It is automatic, scoped to one session, usually one transaction, and it guarantees that loading the same id twice inside the session returns the same object. It disappears when the session closes.</p>\n<p>The second level cache is the opposite in every respect: it is opt in, scoped to the <code>SessionFactory</code>, so shared by every session and every request, and it survives across transactions. It stores the <strong>state</strong> of an entity, not the entity object, so each session still builds its own instance from the cached data.</p>\n<table><thead><tr><th></th><th>First level</th><th>Second level</th></tr></thead><tbody><tr><td>Scope</td><td>One session</td><td>The whole <code>SessionFactory</code></td></tr><tr><td>Enabled</td><td>Always</td><td>Only when configured, per entity</td></tr><tr><td>Lifetime</td><td>Until the session closes</td><td>Until evicted or expired</td></tr><tr><td>Stores</td><td>Managed entity instances</td><td>Disassembled entity state</td></tr><tr><td>Consistency risk</td><td>None inside the session</td><td>Stale data across sessions and nodes</td></tr><tr><td>Provider</td><td>Hibernate itself</td><td>A cache implementation through JCache</td></tr></tbody></table>\n<p>The order of lookups on <code>entityManager.find(Country.class, 1L)</code> is: the persistence context first, then the second level cache if the entity is cacheable, then the database. A hit at either level means no SQL.</p>\n<h2>What gets cached, and what does not</h2>\n<p>Four kinds of data can live in the second level cache, each in its own region:</p>\n<ol><li><strong>Entity data.</strong> The column values of an entity, keyed by its id. Hit by <code>find</code>, <code>getReference</code> initialisation and loading a to-one association.</li><li><strong>Collection data.</strong> For a mapped collection, only the <strong>ids</strong> of the elements, keyed by owner id. The elements themselves must be cached as entities for the collection cache to avoid SQL.</li><li><strong>Natural id mappings.</strong> A map from a business key such as <code>code</code> to the primary key, so a lookup by natural id avoids a query.</li><li><strong>Query results.</strong> The list of ids that a particular query with particular parameters returned, plus a timestamp. This is the query cache, separate from the others and off by default.</li></ol>\n<p>What it does not do is just as important. A JPQL query such as <code>from Product p where p.price &gt; 10</code> is not served from the entity cache. The query goes to the database; the entity cache helps only when Hibernate then needs to load an entity by id. This surprises people who mark an entity cacheable and expect every query to speed up. Only lookups by identifier benefit, unless you also enable the query cache.</p>\n<h2>The life of a cache entry</h2>\n<p>It helps to see what actually sits in the cache, because several surprises follow from it. When Hibernate loads a <code>Product</code> row, it does not store the <code>Product</code> object. It <strong>disassembles</strong> the entity into an array of values in the order of the mapped properties, with associations reduced to their ids, and stores that array under a key made of the entity name, the id and the tenant. A later hit <strong>assembles</strong> a new <code>Product</code> from the array. That has three consequences. Each session gets its own instance, so the cache can never hand two threads the same mutable object. Associations in a cached entity are ids and are resolved lazily or eagerly as usual, which is why a cache hit on <code>Product</code> does not mean <code>origin</code> is loaded. And a cached entry is a snapshot: nothing keeps it synchronised except Hibernate's own invalidation.</p>\n<p>The sequence for a cold read is: look in the persistence context, miss; look in the second level cache, miss; run the <code>SELECT</code>; put the disassembled state into the cache; return the entity. The sequence for a warm read in a new session is: persistence context miss; cache hit; assemble; return. For a write under <code>READ_WRITE</code> there are more steps, covered next.</p>\n<h2>Concurrency strategies</h2>\n<p>Marking an entity cacheable requires choosing a <strong>concurrency strategy</strong>, which defines the consistency guarantee:</p>\n<table><thead><tr><th>Strategy</th><th>Writes allowed</th><th>Guarantee</th><th>Cost</th></tr></thead><tbody><tr><td><code>READ_ONLY</code></td><td>No</td><td>Entry never changes</td><td>Lowest; an update throws</td></tr><tr><td><code>NONSTRICT_READ_WRITE</code></td><td>Yes</td><td>Eventual: entry evicted after commit, brief stale window</td><td>Low</td></tr><tr><td><code>READ_WRITE</code></td><td>Yes</td><td>No stale reads of committed data, using soft locks</td><td>Medium</td></tr><tr><td><code>TRANSACTIONAL</code></td><td>Yes</td><td>Participates in a JTA transaction</td><td>Needs a transactional cache provider</td></tr></tbody></table>\n<p><code>READ_ONLY</code> is for reference data you never change through the application: countries, currencies, a fixed list of roles. It is the fastest and the safest, since the cache never needs to be reconciled with a write. <code>READ_WRITE</code> is the default choice for data that does change: when a transaction updates the entity, Hibernate places a <strong>soft lock</strong> on the cache entry, so other transactions bypass the cache and read from the database until the update commits, after which the entry is replaced. <code>NONSTRICT_READ_WRITE</code> skips the soft lock and evicts the entry after the transaction, accepting that another session may read the old value in the short window between commit and eviction. Use it only when a brief stale read is harmless. <code>TRANSACTIONAL</code> needs a JTA setup and a provider that supports it, which excludes the common JCache providers, so most Spring Boot applications never use it.</p>\n<h2>The READ_WRITE strategy in motion</h2>\n<p>The strategies are easiest to understand as a timeline. Two transactions, T1 updating a product's name and T2 reading the same product while T1 is still open, under <code>READ_WRITE</code>:</p>\n<ol><li>T1 loads the product (from the cache or the database) and calls <code>setName</code>.</li><li>T1 flushes. Hibernate runs the <code>UPDATE</code> and <strong>soft locks</strong> the cache entry: it replaces the cached state with a lock marker carrying a timestamp.</li><li>T2 asks for the product, finds the lock marker, treats it as a miss and reads the database. Under <code>READ COMMITTED</code> the database still shows the old name, because T1 has not committed. T2 does not write to the cache while the entry is locked.</li><li>T1 commits. After the commit, Hibernate releases the lock and stores the new state in the cache.</li><li>A later read from T3 hits the cache and sees the new name.</li></ol>\n<p>The soft lock is why <code>READ_WRITE</code> never serves a stale value that has been replaced by a committed write, and the price is that during a write, readers go to the database. If the transaction rolls back at step 4, the lock is released and the old state is not restored from the lock but evicted, so the next read repopulates it.</p>\n<p>A test makes the behaviour concrete, using two threads. The structure is the barrier test from <a href=\"/library/lost-update-jpa-handle-concurrent-updates\">losing updates in JPA</a>: T1 updates and waits before committing, T2 reads and asserts it saw the old value from the database and not a half applied state.</p>\n<pre><code class=\"language-java\">@Test\nvoid readerDuringAnUncommittedWriteSeesTheOldCommittedValue() throws Exception {\n    var updated = new CountDownLatch(1);\n    var mayCommit = new CountDownLatch(1);\n    var tx = new TransactionTemplate(tm);\n\n    var writer = CompletableFuture.runAsync(() -&gt; tx.executeWithoutResult(s -&gt; {\n        Product p = products.findById(id).orElseThrow();\n        p.rename(\"New name\");\n        products.flush();                    // UPDATE sent, soft lock placed\n        updated.countDown();\n        await(mayCommit);\n    }));\n\n    updated.await();\n    String seen = loadNameInNewSession(id);  // reader must not see \"New name\" yet\n    mayCommit.countDown();\n    writer.join();\n\n    assertThat(seen).isEqualTo(\"Old name\");\n    assertThat(loadNameInNewSession(id)).isEqualTo(\"New name\");\n}</code></pre>\n<h2>Sizing a region</h2>\n<p>A heap limit on entries is a guess until you do the arithmetic. Suppose <code>Product</code> has 40,000 rows and you cache 20,000 entries. The question is how much memory that is and whether it covers the traffic. Estimate the size of one disassembled entry: an id, a name of about 40 characters (roughly 100 bytes as a Java string with its header), a few numbers and ids, plus the cache provider's per entry overhead of around 100 to 200 bytes. Call it 400 bytes. Twenty thousand entries is then about 8 MB, which is nothing on a service with a gigabyte of heap.</p>\n<p>The second question is coverage. If requests follow a typical skewed pattern in which a small fraction of products draws most of the reads, a cache holding half the rows can still deliver a high hit ratio. If the access pattern is uniform, a cache holding half the rows gives about half hits. Only the statistics from a real workload answer this, which is why measurement belongs before the decision. Start generous, since 8 MB is cheap, watch the eviction counts in the provider's statistics, and shrink only if memory is genuinely tight. For entities with big columns, use a size limit in bytes: Ehcache 3 supports <code>&lt;heap unit=\"MB\"&gt;64&lt;/heap&gt;</code>, which sizes the tier by memory rather than count, at the cost of the provider measuring object graphs.</p>\n<h2>Using Caffeine as the provider</h2>\n<p>If Caffeine is already your local cache, its JCache module avoids a second library. The configuration is a different file but the same idea, and the provider class changes:</p>\n<pre data-filename=\"src/main/resources/application.yaml\"><code class=\"language-yaml\">spring:\n  jpa:\n    properties:\n      hibernate:\n        cache:\n          use_second_level_cache: true\n          region.factory_class: jcache\n        javax.cache:\n          provider: com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider\n          uri: classpath:caffeine.conf</code></pre>\n<pre data-filename=\"src/main/resources/caffeine.conf\"><code class=\"language-text\">caffeine.jcache {\n  default {\n    policy.maximum.size = 10000\n    policy.eager-expiration.after-write = 30m\n    monitoring.statistics = true\n  }\n  \"dev.javahacks.catalog.Country\" {\n    policy.maximum.size = 300\n  }\n  \"default-update-timestamps-region\" {\n    policy.maximum.size = 5000\n  }\n}</code></pre>\n<p>The file is in HOCON format, a superset of JSON. The <code>default</code> block applies to any region without its own entry, a convenience that Ehcache's XML does not offer. Caffeine evicts with the Window TinyLFU policy and is a good performer, but it has no off heap or disk tier; if you need those, Ehcache is the provider.</p>\n<h2>Step 1: add a provider</h2>\n<p>Hibernate does not ship a cache; it defines an SPI and the <code>hibernate-jcache</code> module adapts any JCache (JSR 107) implementation to it. Two providers are common. Ehcache 3 is the long standing one, and Caffeine's JCache module is the choice if you already use Caffeine elsewhere. Add the adapter and one provider:</p>\n<pre data-filename=\"pom.xml\"><code class=\"language-xml\">&lt;dependency&gt;\n    &lt;groupId&gt;org.hibernate.orm&lt;/groupId&gt;\n    &lt;artifactId&gt;hibernate-jcache&lt;/artifactId&gt;\n&lt;/dependency&gt;\n&lt;dependency&gt;\n    &lt;groupId&gt;org.ehcache&lt;/groupId&gt;\n    &lt;artifactId&gt;ehcache&lt;/artifactId&gt;\n    &lt;classifier&gt;jakarta&lt;/classifier&gt;\n&lt;/dependency&gt;</code></pre>\n<p>The <code>jakarta</code> classifier matters on Ehcache 3: the default artifact references <code>javax.xml.bind</code>, which breaks on current runtimes. Spring Boot manages the Hibernate version, so <code>hibernate-jcache</code> needs no version number. For Caffeine, depend on <code>com.github.ben-manes.caffeine:jcache</code> instead and set the provider class accordingly in the next step.</p>\n<p>Then switch the cache on:</p>\n<pre data-filename=\"src/main/resources/application.yaml\"><code class=\"language-yaml\">spring:\n  jpa:\n    properties:\n      jakarta.persistence.sharedCache.mode: ENABLE_SELECTIVE\n      hibernate:\n        cache:\n          use_second_level_cache: true\n          use_query_cache: false\n          region.factory_class: jcache\n        javax.cache:\n          provider: org.ehcache.jsr107.EhcacheCachingProvider\n          uri: classpath:ehcache.xml\n        generate_statistics: true</code></pre>\n<p><code>ENABLE_SELECTIVE</code> means only entities annotated as cacheable are stored, the safe default; the alternative, <code>ALL</code>, caches every entity and almost always caches things you did not mean to. <code>generate_statistics</code> is on here because the later sections rely on it, and it should be considered a development and staging setting, since statistics add a little overhead.</p>\n<h2>Step 2: mark an entity</h2>\n<p>Two annotations do the work: <code>@Cacheable</code> from Jakarta Persistence, saying the entity is eligible, and <code>@Cache</code> from Hibernate, choosing the strategy. A stable reference entity:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/catalog/Country.java\"><code class=\"language-java\">package dev.javahacks.catalog;\n\nimport jakarta.persistence.*;\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\nimport org.hibernate.annotations.NaturalId;\nimport org.hibernate.annotations.NaturalIdCache;\n\n@Entity\n@Cacheable\n@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)\n@NaturalIdCache\npublic class Country {\n    @Id\n    private Long id;\n\n    @NaturalId\n    @Column(nullable = false, length = 2, updatable = false)\n    private String code;\n\n    @Column(nullable = false)\n    private String name;\n\n    protected Country() {}\n\n    public Country(Long id, String code, String name) {\n        this.id = id;\n        this.code = code;\n        this.name = name;\n    }\n\n    public Long getId() { return id; }\n    public String getCode() { return code; }\n    public String getName() { return name; }\n}</code></pre>\n<p>And a regional entity that does change, with a to-one association that will be resolved from the cache:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/catalog/Product.java\"><code class=\"language-java\">@Entity\n@Cacheable\n@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)\npublic class Product {\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE)\n    private Long id;\n\n    private String name;\n\n    @ManyToOne(fetch = FetchType.LAZY, optional = false)\n    private Country origin;\n\n    @ElementCollection\n    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)\n    private Set&lt;String&gt; tags = new HashSet&lt;&gt;();\n\n    // constructors and accessors omitted\n}</code></pre>\n<p>The <code>@Cache</code> on <code>tags</code> caches the collection, which, as noted above, stores only the element values for a basic collection; for an association between entities it stores ids. Without that second annotation the collection is loaded from the database every time, even when its owner is cached.</p>\n<h2>Step 3: configure regions</h2>\n<p>Each cached entity gets a region named after its fully qualified class. Without configuration, the JCache provider applies a default, and for Ehcache 3 that can mean entries that never expire, which is the setting you least want on <code>READ_WRITE</code> data. Give every region a size and a time to live in <code>ehcache.xml</code>:</p>\n<pre data-filename=\"src/main/resources/ehcache.xml\"><code class=\"language-xml\">&lt;config xmlns=\"http://www.ehcache.org/v3\"\n        xmlns:jsr107=\"http://www.ehcache.org/v3/jsr107\"&gt;\n\n    &lt;service&gt;\n        &lt;jsr107:defaults enable-statistics=\"true\"/&gt;\n    &lt;/service&gt;\n\n    &lt;cache alias=\"dev.javahacks.catalog.Country\"&gt;\n        &lt;expiry&gt;&lt;none/&gt;&lt;/expiry&gt;\n        &lt;heap unit=\"entries\"&gt;300&lt;/heap&gt;\n    &lt;/cache&gt;\n\n    &lt;cache alias=\"dev.javahacks.catalog.Product\"&gt;\n        &lt;expiry&gt;&lt;ttl unit=\"minutes\"&gt;30&lt;/ttl&gt;&lt;/expiry&gt;\n        &lt;heap unit=\"entries\"&gt;20000&lt;/heap&gt;\n    &lt;/cache&gt;\n\n    &lt;cache alias=\"dev.javahacks.catalog.Product.tags\"&gt;\n        &lt;expiry&gt;&lt;ttl unit=\"minutes\"&gt;30&lt;/ttl&gt;&lt;/expiry&gt;\n        &lt;heap unit=\"entries\"&gt;20000&lt;/heap&gt;\n    &lt;/cache&gt;\n\n    &lt;cache alias=\"default-update-timestamps-region\"&gt;\n        &lt;expiry&gt;&lt;none/&gt;&lt;/expiry&gt;\n        &lt;heap unit=\"entries\"&gt;5000&lt;/heap&gt;\n    &lt;/cache&gt;\n\n    &lt;cache alias=\"default-query-results-region\"&gt;\n        &lt;expiry&gt;&lt;ttl unit=\"minutes\"&gt;10&lt;/ttl&gt;&lt;/expiry&gt;\n        &lt;heap unit=\"entries\"&gt;1000&lt;/heap&gt;\n    &lt;/cache&gt;\n&lt;/config&gt;</code></pre>\n<p>Read the choices. <code>Country</code> never expires because it is read only and tiny: there are fewer than 300 countries. <code>Product</code> expires after thirty minutes, a safety net so that a missed invalidation heals itself, and holds at most twenty thousand entries so the heap use is bounded. The two <code>default-</code> regions are Hibernate's own and must exist if you use the query cache: the update timestamps region must never evict entries, or the query cache would serve results it should have invalidated. If Hibernate cannot find a region configured, Ehcache creates one with defaults and logs a warning, so scan the startup log for it.</p>\n<h2>Step 4: prove it works</h2>\n<p>Never assume a cache is working. Make a test that asserts the database is not touched. Hibernate's statistics expose second level hits and misses:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/catalog/SecondLevelCacheTest.java\"><code class=\"language-java\">@SpringBootTest\n@Testcontainers\nclass SecondLevelCacheTest {\n\n    @Container\n    @ServiceConnection\n    static PostgreSQLContainer&lt;?&gt; db = new PostgreSQLContainer&lt;&gt;(\"postgres:17\");\n\n    @Autowired EntityManagerFactory emf;\n    @Autowired CountryRepository countries;\n\n    @Test\n    void secondLookupInANewSessionIsServedFromTheCache() {\n        countries.saveAndFlush(new Country(1L, \"VN\", \"Vietnam\"));\n        Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();\n        emf.getCache().evictAll();\n        stats.clear();\n\n        loadCountryInNewSession(1L);          // miss: goes to the database and populates the cache\n        loadCountryInNewSession(1L);          // hit: no SQL\n\n        assertThat(stats.getSecondLevelCacheMissCount()).isEqualTo(1);\n        assertThat(stats.getSecondLevelCacheHitCount()).isEqualTo(1);\n        assertThat(stats.getPrepareStatementCount()).isEqualTo(1);   // one SELECT in total\n    }\n\n    private void loadCountryInNewSession(Long id) {\n        try (var em = emf.createEntityManager()) {\n            assertThat(em.find(Country.class, id)).isNotNull();\n        }\n    }\n}</code></pre>\n<p>The second lookup happens in a brand new <code>EntityManager</code>, which has an empty first level cache, so a hit can only come from the second level. <code>getPrepareStatementCount</code> confirms the claim at the level that matters: JDBC statements prepared. The same trick is the regression test that keeps the cache from silently vanishing when someone removes an annotation. Statements counted in other ways are in <a href=\"/library/hibernate-log-sql-statistics-count-statements\">logging SQL and counting statements</a>.</p>\n<p>You can also see it in the SQL log. With <code>spring.jpa.show-sql=true</code> the first <code>find</code> prints a <code>select</code> and the second prints nothing.</p>\n<h2>Caching to-one associations</h2>\n<p>The most valuable effect of an entity cache is not <code>find</code> calls in your code but association loads. A <code>Product</code> has a lazy <code>origin</code>. When code touches <code>product.getOrigin().getName()</code>, Hibernate initialises the proxy by loading <code>Country</code> by id. With <code>Country</code> cached, that is a memory read, not a query, so a page that lists two hundred products and shows each origin goes from 201 statements to one, with no change to the query. This is the case where the second level cache and the N plus 1 problem meet, and it is a legitimate fix for reference data: see <a href=\"/library/hibernate-n-plus-1-problem-fix\">the N plus 1 problem and its fixes</a> for the other tools, such as fetch joins and batch fetching, which should usually come first because they work for any data.</p>\n<h2>Collection caching and its trap</h2>\n<p>A cached collection stores element ids under the owner's id. Loading <code>product.getTags()</code> from the cache reads the ids, and then, for entity elements, Hibernate loads each element by id, from the entity cache if it is cacheable and from the database if not. So a cached collection of non cacheable entities makes things worse than no cache at all: one fewer query to find the ids, then one query per element. The rule is to cache a collection only when its element type is also cacheable, or the elements are basic values.</p>\n<p>The second consequence is invalidation. Any change to the collection, adding a tag, evicts the collection entry for that owner. A collection that changes often has a cache entry that is rarely valid, and the cache is pure overhead.</p>\n<h2>Natural id caching</h2>\n<p><code>@NaturalIdCache</code> on <code>Country</code> stores the mapping from <code>code</code> to <code>id</code>. Then a lookup by business key avoids the query that would otherwise be needed to find the primary key:</p>\n<pre><code class=\"language-java\">Country vn = session.bySimpleNaturalId(Country.class).load(\"VN\");</code></pre>\n<p>The natural id must be immutable, or the mapping goes stale, which is why the example marks the column <code>updatable = false</code>. The pattern is described in <a href=\"/library/hibernate-natural-id-use-ids-business\">natural ids in Hibernate</a>. In Spring Data you reach it through a custom repository fragment, since derived queries like <code>findByCode</code> are ordinary queries and are not served from this cache.</p>\n<h2>The query cache</h2>\n<p>The query cache stores the <strong>result ids</strong> of a query for a specific set of parameters. It is separate, must be enabled twice, and is the part of the second level cache that disappoints most often. Turn on the property and mark each query as cacheable:</p>\n<pre><code class=\"language-java\">public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {\n\n    @QueryHints(@QueryHint(name = \"org.hibernate.cacheable\", value = \"true\"))\n    @Query(\"select p from Product p where p.origin.code = :code order by p.name\")\n    List&lt;Product&gt; findByOriginCode(@Param(\"code\") String code);\n}</code></pre>\n<pre><code class=\"language-yaml\">spring.jpa.properties.hibernate.cache.use_query_cache: true</code></pre>\n<p>How it stays correct: Hibernate records, in the update timestamps region, the time of the last change to each table. A cached query result carries the time it was stored. On lookup, if any table that the query touches was modified after that time, the result is discarded. The consequence is that <strong>any write to the table invalidates every cached query on it</strong>, not just queries that would be affected. On a table that is written every few seconds, the query cache hit ratio is close to zero and each query pays the cost of storing results that are immediately dead.</p>\n<p>It is worth it in a narrow case: queries over rarely changing tables, repeated with a small set of parameter values. A <code>findByOriginCode</code> over products that change once a day fits. A dashboard query over an orders table does not. Because the query cache returns ids only, the entities themselves should be in the entity cache, or each hit still costs one query per row, the same trap as collections. Decide on evidence: enable it, look at the hit ratio, and turn it off if the ratio is low.</p>\n<h2>Cache modes: bypassing and refreshing</h2>\n<p>Sometimes a single operation must ignore the cache, for instance an admin screen that must show the true database state, or a job that loads a lot of data and should not push everything else out. Jakarta Persistence defines two modes, set per operation or per session:</p>\n<pre><code class=\"language-java\">Map&lt;String, Object&gt; hints = Map.of(\n        \"jakarta.persistence.cache.retrieveMode\", CacheRetrieveMode.BYPASS,\n        \"jakarta.persistence.cache.storeMode\", CacheStoreMode.REFRESH);\n\nProduct fresh = em.find(Product.class, id, hints);</code></pre>\n<p><code>CacheRetrieveMode.BYPASS</code> skips reading the cache. <code>CacheStoreMode.REFRESH</code> writes the freshly loaded state back, replacing a possibly stale entry, while <code>BYPASS</code> as the store mode leaves the cache alone, the right choice for a batch read of millions of rows. Manual eviction is available through the standard API:</p>\n<pre><code class=\"language-java\">Cache cache = emf.getCache();\ncache.evict(Product.class, id);       // one entity\ncache.evict(Product.class);           // every Product\ncache.evictAll();                      // everything, including query results</code></pre>\n<p>Expose a protected admin operation that calls these, because the day will come when a data fix is applied directly in the database and the application must be told.</p>\n<h2>Consistency: what invalidates what</h2>\n<p>Hibernate keeps the cache correct only for changes it knows about. Know the list.</p>\n<p><strong>Writes through entities</strong> update or evict the entry as the strategy dictates. That is the case Hibernate handles well.</p>\n<p><strong>Bulk JPQL statements</strong> such as <code>update Product p set p.price = ...</code> bypass the entity lifecycle. Hibernate does invalidate the affected regions, evicting every cached <code>Product</code>, because it cannot know which rows changed. Correct, but it throws away the whole region, a cost to remember when you run a bulk update frequently. The details of what bulk statements skip are in <a href=\"/library/jpa-bulk-update-delete-updates-deletes\">bulk updates and deletes in JPA</a>.</p>\n<p><strong>Native SQL</strong> is opaque. By default, a native query that modifies data evicts all second level cache regions, which is safe and drastic. You can narrow it by declaring the tables it touches:</p>\n<pre><code class=\"language-java\">em.createNativeQuery(\"update product set price = price * 0.9 where category_id = :c\")\n        .unwrap(org.hibernate.query.NativeQuery.class)\n        .addSynchronizedEntityClass(Product.class)       // evict only Product, not everything\n        .setParameter(\"c\", 12)\n        .executeUpdate();</code></pre>\n<p><strong>Writes by anyone else</strong> are invisible. A second service that shares the database, a DBA fixing a row, an import script run in <code>psql</code>: none of them tell your cache. This is the real boundary of the feature. If another application writes the same tables, either give the regions a short time to live, so staleness is bounded by minutes, or do not cache those entities at all. The TTL in <code>ehcache.xml</code> is not an optimisation, it is your correctness bound.</p>\n<h2>Several application nodes</h2>\n<p>Everything above describes one JVM. With four replicas each has its own cache, each warmed independently, and an update handled by node A evicts the entry in node A only. Nodes B, C and D keep serving the old state until their entries expire. For <code>READ_ONLY</code> reference data this is a non issue. For <code>READ_WRITE</code> data that users can see change, it is a visible bug: a customer edits a product, refreshes the page and, depending on which node answers, sees the old or the new version.</p>\n<p>There are three ways out. <strong>Accept a short TTL.</strong> If a minute of staleness is acceptable, a one minute TTL bounds the damage and needs no infrastructure. <strong>Use a clustered provider</strong> that propagates invalidations or shares the data, which means a different <code>region.factory_class</code> such as Infinispan's, Hazelcast's or a Redis based region factory, with the cost of a network hop per cache access and the operational weight of the cluster; the comparison is in <a href=\"/library/redis-vs-hazelcast-infinispan-java\">Redis versus Hazelcast versus Infinispan</a>. Or <strong>cache only what never changes</strong> and keep volatile entities out. For most applications the third option, combined with a Spring-level cache for specific computed answers, is the right size.</p>\n<p>If you run only one instance by design, such as a desktop style deployment, the local cache is fully consistent and you can use <code>READ_WRITE</code> without further worry, except for the external writer case above.</p>\n<h2>Measure the benefit</h2>\n<p>A cache that does not hit is a memory cost. Statistics tell you whether each region earns its place. Print them for development, and export them in production with Micrometer, which Spring Boot binds to Hibernate automatically when statistics are on:</p>\n<pre><code class=\"language-java\">Statistics stats = sessionFactory.getStatistics();\nfor (String region : stats.getSecondLevelCacheRegionNames()) {\n    CacheRegionStatistics r = stats.getDomainDataRegionStatistics(region);\n    long total = r.getHitCount() + r.getMissCount();\n    double ratio = total == 0 ? 0 : (double) r.getHitCount() / total;\n    System.out.printf(\"%-50s hits=%d misses=%d puts=%d ratio=%.2f%n\",\n            region, r.getHitCount(), r.getMissCount(), r.getPutCount(), ratio);\n}</code></pre>\n<pre><code class=\"language-text\">dev.javahacks.catalog.Country                      hits=48211 misses=3 puts=3 ratio=1.00\ndev.javahacks.catalog.Product                      hits=1204 misses=7311 puts=7311 ratio=0.14\ndev.javahacks.catalog.Product.tags                 hits=0 misses=912 puts=912 ratio=0.00</code></pre>\n<p>That sample output (illustrative figures, not a measurement) shows the three outcomes you will see. <code>Country</code> is the ideal: three misses to warm up, then all hits. <code>Product</code> has a ratio of fourteen percent, which says the working set is larger than the cache or the entries are being invalidated by writes faster than they are read. Raise the size or drop the cache from that entity. <code>Product.tags</code> has zero hits, so the collection cache costs memory and puts for nothing. A reasonable policy: remove the annotation from any region whose ratio stays below about half after a representative period, since each miss on a <code>READ_WRITE</code> region also pays for a put.</p>\n<p>With Actuator and Micrometer on, the metrics <code>hibernate.second.level.cache.requests</code> tagged <code>result=hit</code> and <code>result=miss</code> give you the same figures on a dashboard.</p>\n<h2>The Spring Cache alternative</h2>\n<p>The second level cache works at the persistence layer and only by id. Often a cleaner approach is caching at the service layer with Spring's cache abstraction, keyed by whatever makes sense, storing DTOs or computed results rather than entities:</p>\n<pre><code class=\"language-java\">@Service\npublic class CountryLookup {\n    private final CountryRepository countries;\n\n    public CountryLookup(CountryRepository countries) {\n        this.countries = countries;\n    }\n\n    @Cacheable(cacheNames = \"countryByCode\", key = \"#code\")\n    public CountryView byCode(String code) {\n        Country c = countries.findByCode(code).orElseThrow();\n        return new CountryView(c.getCode(), c.getName());\n    }\n}</code></pre>\n<table><thead><tr><th></th><th>Hibernate L2</th><th>Spring <code>@Cacheable</code></th></tr></thead><tbody><tr><td>Keyed by</td><td>Entity id or natural id</td><td>Any method argument</td></tr><tr><td>Stores</td><td>Entity state</td><td>Whatever the method returns</td></tr><tr><td>Invalidated by</td><td>Hibernate on its own writes</td><td>You, with <code>@CacheEvict</code>, or a TTL</td></tr><tr><td>Hit saves</td><td>Entity loads and association initialisation</td><td>The whole method, including queries and mapping</td></tr><tr><td>Surprises</td><td>Silent staleness from outside writes</td><td>Forgotten evictions</td></tr></tbody></table>\n<p>They are not exclusive. A reasonable stack for reference data is Hibernate L2 with <code>READ_ONLY</code> for the entities and Spring caching for aggregated answers built from them. If you already use Caffeine at the service layer, <a href=\"/library/caffeine-vs-guava-cache-ehcache\">Caffeine versus Guava versus Ehcache</a> covers choosing the library.</p>\n<h2>Projections and DTO queries bypass the entity cache</h2>\n<p>A related misunderstanding is expecting the cache to speed up projections. A query such as <code>select new dev.javahacks.catalog.ProductView(p.id, p.name) from Product p</code> returns values, not entities, so there is nothing to assemble from the entity cache and it always hits the database. The same holds for Spring Data interface projections. That is fine and often preferable for list screens, where you want narrow rows, but it means the cache helps loads by id and association navigation, not these queries. <a href=\"/library/hibernate-dto-projection-use-projections-records\">DTO projections with records</a> shows when narrow queries are the faster option anyway.</p>\n<h2>Multi tenancy</h2>\n<p>In a multi tenant application the cache key includes the tenant identifier, so two tenants never share an entry, which is correct by default. The consequence is that cache size has to account for tenants times rows. If one tenant has a million products, a twenty thousand entry limit is shared among everyone and the hot tenant evicts the others. See <a href=\"/library/hibernate-multi-tenancy-implement\">multi tenancy in Hibernate</a> for how tenancy is identified, and size regions with the biggest tenant in mind.</p>\n<h2>Troubleshooting guide</h2>\n<p>When the cache does not behave, work from the symptom:</p>\n<table><thead><tr><th>Symptom</th><th>Likely cause</th><th>Check</th></tr></thead><tbody><tr><td>No hits at all, SQL on every find</td><td>Entity not <code>@Cacheable</code> or no <code>@Cache</code>, or L2 disabled</td><td>Property <code>use_second_level_cache</code>, annotations, startup log</td></tr><tr><td>Hits in tests, misses in production</td><td>Different <code>sharedCache.mode</code> or region config</td><td>Compare effective properties on both</td></tr><tr><td>Stale value after a direct database change</td><td>Writer outside Hibernate</td><td>TTL, manual <code>evict</code> after the change</td></tr><tr><td>Stale value on one node only</td><td>Per-node cache, no invalidation propagation</td><td>Cluster provider or short TTL</td></tr><tr><td><code>Can't write to a readonly object</code></td><td>Update on a <code>READ_ONLY</code> entity</td><td>Switch to <code>READ_WRITE</code></td></tr><tr><td>Memory growth over days</td><td>No expiry or size limit on a region</td><td>Region config, provider statistics</td></tr><tr><td>Query cache never hits</td><td>Table written constantly, or parameters vary widely</td><td>Timestamps region, hit ratio</td></tr><tr><td>Hit ratio is high but latency did not improve</td><td>The database was not the bottleneck</td><td>Profile the request before caching more</td></tr></tbody></table>\n<p>The last row is the most important lesson. A cache is an answer to a measured problem, and the measurement comes first.</p>\n<h2>A short decision recipe</h2>\n<p>If you take only a page from this guide, take this sequence. Find the queries that dominate by count in a real workload, using statistics. Fix the ones that are plain N plus 1 problems with fetch joins and batch fetching. For what remains, identify entities that are read far more than they are written and that nothing outside the application modifies. Mark those <code>READ_ONLY</code> if they never change and <code>READ_WRITE</code> with a TTL if they do. Prove each with a statement count test. Watch the hit ratio for a week and delete the annotation wherever it is not paying. The result is a small, deliberate set of cached entities, not an application where everything is cached and nothing is understood.</p>\n<h2>A worked scenario: the product catalogue page</h2>\n<p>Pull the pieces together with a realistic request. A catalogue page lists 50 products, each showing its name, its origin country and its tags, and the same page is requested hundreds of times a minute. The naive implementation loads the products with one query, then touches <code>getOrigin()</code> and <code>getTags()</code> per row. With nothing cached, that is one query for the page, up to 50 for the origins and 50 for the tags: 101 statements per request.</p>\n<p>Apply the guide in order. First, fix what needs no cache: a fetch join or batch fetching collapses the origin and tag loads into a handful of statements regardless of whether the data is hot. Say that brings the page to three statements. Second, look at what is left. The product list query is dynamic and changes with every filter, so it is a poor candidate for the query cache. The origins, though, are the same two hundred countries on every page, so marking <code>Country</code> as <code>READ_ONLY</code> removes the origin statements entirely, leaving two. The tags depend on the products, which change when editors work, so a <code>READ_WRITE</code> collection cache would be invalidated by every edit. Measure first: if editors change a product twice a day and the page is requested a thousand times an hour, the collection hit ratio will be excellent and the cache is worth keeping; if the catalogue is edited constantly, drop it.</p>\n<p>The lesson is the order of operations. The cache removed one statement from a page that had already been cut from 101 to three by fixing the query shape, and for the product list itself it does nothing. That is a typical outcome, and it is why this guide keeps repeating that the cache is the last step and the measurement is the first.</p>\n<h2>Frequently met questions</h2>\n<p>**Does <code>find</code> always use the cache?** Only if the entity is cacheable and the session's retrieve mode is <code>USE</code>, the default. A <code>JOIN FETCH</code> query does not consult the entity cache for the fetched rows; it reads the joined result and may populate the cache with it.</p>\n<p>**Can the cache hold entities with <code>@Version</code>?** Yes, and it works well with <code>READ_WRITE</code>, because the version is part of the stored state. The optimistic lock check still happens in the <code>UPDATE</code> statement against the database, so a stale cached version results in a conflict exception and not a lost update. The interaction is covered in <a href=\"/library/jpa-optimistic-locking-version-use\">optimistic locking with a version column</a>.</p>\n<p>**Does it work with <code>@Transactional(readOnly = true)</code>?** Yes. Reading from the cache is allowed in read only transactions, and populating it on a miss still happens.</p>\n<p><strong>What about Hibernate Envers or soft deletes?</strong> Audited tables are poor cache candidates because they grow and are read rarely. Soft deleted rows still sit in the table, so a cached entity can represent a row that business rules consider gone; check that your filter is applied on cache hits, which <code>@SQLRestriction</code> does not guarantee for lookups by id.</p>\n<p><strong>Will it survive an application restart?</strong> With the heap based providers shown here, no. The cache starts empty and warms up. A disk tier in Ehcache can persist entries across restarts, at the price of more configuration and the risk of loading stale data after a deployment that changed the entity shape.</p>\n<p><strong>Does the cache break after an entity class changes?</strong> The stored array follows the old property order. In-memory caches are rebuilt on every restart, so a new deployment starts clean. This is another reason clustered or persistent caches need a version in the key or a flush on deploy, as discussed in the section on several nodes.</p>\n<h2>Failure modes</h2>\n<p><strong>Caching volatile entities.</strong> An entity updated several times a minute spends its life in soft locks and evictions. The cache adds work and returns misses. Cache what is read many times per write.</p>\n<p>**<code>READ_ONLY</code> and an update.** An update to a read only entity fails at flush with <code>UnsupportedOperationException: Can't write to a readonly object</code>. If your \"reference data\" turns out to change, switch to <code>READ_WRITE</code> rather than removing the check.</p>\n<p><strong>Missing region configuration.</strong> An entity cached without a configured region uses provider defaults, which may mean no expiry and no size limit, so memory grows without bound. Configure every region and check the startup log for \"missing cache\" warnings.</p>\n<p><strong>Caching large graphs.</strong> An entity with large text or binary columns makes each entry big. A twenty thousand entry limit means little when entries weigh 100 KB. Size by bytes where the provider supports it, or do not cache such entities.</p>\n<p><strong>Detached entities and lazy fields.</strong> A cache hit builds an entity from stored state; lazy associations still load on access. The cache does not remove the need to fetch related data inside the session, and a <code>LazyInitializationException</code> is still possible outside it.</p>\n<p><strong>Double caching.</strong> A Spring <code>@Cacheable</code> over a method that loads cached entities holds the data twice. Pick one layer for each piece of data.</p>\n<p><strong>Tests that pass for the wrong reason.</strong> A test suite that never clears the cache between tests sees data from earlier tests. Evict in a <code>@BeforeEach</code> with <code>emf.getCache().evictAll()</code>.</p>\n<h2>Operating it</h2>\n<p>Before enabling in production, run through a short checklist. Every cached entity has a deliberate strategy and a region with a size and a TTL. The startup log shows no missing region warnings. A test asserts the hit and statement counts for the one lookup you care about. The statistics or Micrometer metrics are on a dashboard, with an alert on a collapsing hit ratio. Writers outside the application are known, and their tables are either excluded or given a TTL that matches how long staleness is tolerable. And there is a documented way to evict, because someone will need it.</p>\n<h2>When this does not apply</h2>\n<p>If the same rows are read once and never again, no cache helps. If your bottleneck is a missing index or a bad query plan, fix that first; a cache in front of a slow query only hides it until a miss. <a href=\"/library/slow-query-java-explain-read-plan\">Reading a slow query plan</a> is the tool for that. If correctness requires always reading the latest committed value, such as balances or stock, do not cache it. And if the number of distinct rows is far larger than any memory you can give the cache, the hit ratio will be low by arithmetic, and a read replica or better indexing is the answer. For the primary sources, read the <a href=\"https://docs.jboss.org/hibernate/orm/7.0/userguide/html_single/Hibernate_User_Guide.html#caching\">Hibernate user guide chapter on caching</a>, the <a href=\"https://jcp.org/en/jsr/detail?id=107\">JCache specification overview</a> and the <a href=\"https://www.ehcache.org/documentation/3.10/\">Ehcache 3 documentation</a>.</p>","date_published":"2026-11-14T04:17:31+00:00","tags":["Hibernate"]},{"id":"https://javahacks.dev/library/java-reflection-basics-not-use","url":"https://javahacks.dev/library/java-reflection-basics-not-use","title":"Java Reflection Guide From Basics to When Not to Use It","summary":"A complete guide to Java reflection: inspect and invoke classes, proxies, method handles, modules, performance, native image limits and when not to use it.","content_html":"<p>Frameworks seem to know everything about your code. Spring finds your <code>@Service</code> classes without being told they exist. Jackson fills your record from JSON without a line of mapping code. JUnit discovers methods named nothing in particular and runs the ones annotated <code>@Test</code>. None of that is magic and none of it is generated by a compiler plugin: it is <strong>reflection</strong>, the part of Java that lets a running program look at its own classes, ask what they contain and use them. Learning reflection makes the frameworks understandable, and makes their error messages readable. It also teaches when not to write it, because reflection costs you things Java is otherwise good at: compile time checking, fast calls and a clear picture of who depends on what.</p>\n<p>This guide builds from the first <code>Class</code> object to a small dependency injection container and an object mapper, covering what each step costs. Every section has code you can run on JDK 25. The reading order is the order of power: inspect, read and write, invoke, create, proxy, then the modern alternatives, then the limits. The core idea fits in one sentence worth keeping: <strong>reflection turns names, as strings, into behaviour, and every problem with it comes from the fact that the compiler cannot check a string.</strong></p>\n<p>If you want to attach your own metadata to classes, the companion post is <a href=\"/library/java-custom-annotation-annotations-write-one\">writing a custom annotation in Java</a>, and for the generics half of the story, <a href=\"/library/java-type-erasure-breaks-runtime\">type erasure and what it breaks</a> explains why some information is not available even to reflection.</p>\n<h2>The three ways to get a Class</h2>\n<p>Everything starts with a <code>java.lang.Class</code> object, the run time representation of a type. There are three ordinary ways to obtain one:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/GetClass.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\npublic class GetClass {\n    public static void main(String[] args) throws Exception {\n        Class&lt;?&gt; byLiteral = String.class;                        // compile time known\n        Class&lt;?&gt; byInstance = \"hello\".getClass();                  // from an object\n        Class&lt;?&gt; byName = Class.forName(\"java.util.ArrayList\");    // from a string, at run time\n\n        System.out.println(byLiteral.getName());     // java.lang.String\n        System.out.println(byInstance == byLiteral); // true: one Class object per type per loader\n        System.out.println(byName.getSimpleName());  // ArrayList\n\n        Class&lt;?&gt; missing = Class.forName(\"com.example.DoesNotExist\");\n    }\n}</code></pre>\n<pre><code class=\"language-text\">java.lang.String\ntrue\nArrayList\nException in thread \"main\" java.lang.ClassNotFoundException: com.example.DoesNotExist</code></pre>\n<p>The literal form, <code>String.class</code>, is checked by the compiler and is what you use when you know the type. <code>getClass()</code> gives the <strong>runtime</strong> type of an object, which may be a subclass of the declared type. <code>Class.forName</code> is the dynamic one: the name is a string, so a typo is a run time <code>ClassNotFoundException</code> and a class that is on the classpath but initialises badly gives <code>ExceptionInInitializerError</code> or <code>NoClassDefFoundError</code> instead. Keep these two straight: <code>ClassNotFoundException</code> means \"looked and it was absent\", while <code>NoClassDefFoundError</code> means \"present at compile time and missing now\", covered in <a href=\"/library/classnotfoundexception-fix-noclassdeffounderror\">fixing ClassNotFoundException and NoClassDefFoundError</a>.</p>\n<p>A <code>Class</code> object is per class <strong>loader</strong>. The same class loaded by two loaders gives two distinct <code>Class</code> objects that are not equal, and a cast between them fails with <code>ClassCastException: class X cannot be cast to class X</code>, a confusing message seen with application servers and plugin systems.</p>\n<h2>Inspecting a class</h2>\n<p>From a <code>Class</code> you can ask for its members. The <code>getDeclared...</code> methods return what the class itself declares, including private members, while the plain <code>get...</code> methods return public members including inherited ones. That difference is the most common source of \"why is the method not found\":</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/Inspect.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.*;\nimport java.math.BigDecimal;\nimport java.util.Arrays;\n\npublic class Inspect {\n\n    public static class Invoice {\n        public static final String CURRENCY = \"USD\";\n        private final long id;\n        private BigDecimal total;\n        protected String note;\n\n        public Invoice(long id, BigDecimal total) {\n            this.id = id;\n            this.total = total;\n        }\n\n        public BigDecimal total() { return total; }\n        private void applyDiscount(int percent) {\n            total = total.multiply(BigDecimal.valueOf(100 - percent)).movePointLeft(2);\n        }\n    }\n\n    public static void main(String[] args) {\n        Class&lt;?&gt; type = Invoice.class;\n        System.out.println(\"class: \" + Modifier.toString(type.getModifiers()) + \" \" + type.getName());\n\n        for (Field f : type.getDeclaredFields()) {\n            System.out.printf(\"field  %s %s %s%n\", Modifier.toString(f.getModifiers()), f.getType().getSimpleName(), f.getName());\n        }\n        for (Constructor&lt;?&gt; c : type.getDeclaredConstructors()) {\n            System.out.println(\"ctor   \" + c);\n        }\n        for (Method m : type.getDeclaredMethods()) {\n            System.out.printf(\"method %s %s(%s)%n\", Modifier.toString(m.getModifiers()), m.getName(),\n                    Arrays.stream(m.getParameterTypes()).map(Class::getSimpleName).toList());\n        }\n    }\n}</code></pre>\n<pre><code class=\"language-text\">class: public static dev.javahacks.reflect.Inspect$Invoice\nfield  public static final String CURRENCY\nfield  private final long id\nfield  private BigDecimal total\nfield  protected String note\nctor   public dev.javahacks.reflect.Inspect$Invoice(long,java.math.BigDecimal)\nmethod public BigDecimal total()\nmethod private void applyDiscount([int])</code></pre>\n<p>Note the binary name <code>Inspect$Invoice</code> for a nested class, a detail that shows up in stack traces and in <code>Class.forName</code> strings. The <code>Modifier</code> class decodes the integer bit flags. The order of <code>getDeclaredFields</code> and <code>getDeclaredMethods</code> is <strong>not guaranteed</strong> by the specification: the JVM currently returns declaration order for fields, but code that depends on it breaks on another implementation. If order matters, sort by name or by an annotation value you control.</p>\n<p>Other things you can read from the <code>Class</code>: <code>getSuperclass()</code>, <code>getInterfaces()</code>, <code>isInterface()</code>, <code>isRecord()</code>, <code>isEnum()</code>, <code>isSealed()</code>, <code>getPermittedSubclasses()</code>, <code>getEnclosingClass()</code>, and <code>getModule()</code>. The newer language features are all visible here, a point we return to with records.</p>\n<h2>Reading and writing fields, including private ones</h2>\n<p>A <code>Field</code> object reads and writes the value on an instance. The surprise for newcomers is that private fields are reachable, once you ask for permission with <code>setAccessible(true)</code>:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/FieldAccess.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.Field;\nimport java.math.BigDecimal;\n\npublic class FieldAccess {\n    public static void main(String[] args) throws Exception {\n        var invoice = new Inspect.Invoice(7L, new BigDecimal(\"100.00\"));\n\n        Field total = Inspect.Invoice.class.getDeclaredField(\"total\");\n        total.setAccessible(true);                       // bypass the private modifier\n\n        System.out.println(\"before: \" + total.get(invoice));\n        total.set(invoice, new BigDecimal(\"80.00\"));\n        System.out.println(\"after:  \" + invoice.total());\n\n        Field id = Inspect.Invoice.class.getDeclaredField(\"id\");\n        id.setAccessible(true);\n        System.out.println(\"id: \" + id.getLong(invoice));  // primitive accessor avoids boxing\n    }\n}</code></pre>\n<pre><code class=\"language-text\">before: 100.00\nafter:  80.00\nid: 7</code></pre>\n<p>That is how Hibernate sets entity fields and how Jackson can populate an object with no setters. There are three failure modes to know.</p>\n<p><code>NoSuchFieldException</code> means the name is wrong or the field is declared in a superclass, because <code>getDeclaredField</code> does not search upwards. Walk <code>getSuperclass()</code> yourself if you need inherited fields.</p>\n<p><code>IllegalAccessException</code> means you forgot <code>setAccessible(true)</code> on a non-public member.</p>\n<p><code>InaccessibleObjectException</code> is the modern one, and it appears when you try to open something inside a module that does not allow it, which is most of the JDK itself:</p>\n<pre><code class=\"language-java\">Field value = String.class.getDeclaredField(\"value\");\nvalue.setAccessible(true);</code></pre>\n<pre><code class=\"language-text\">Exception in thread \"main\" java.lang.reflect.InaccessibleObjectException:\nUnable to make field private final byte[] java.lang.String.value accessible:\nmodule java.base does not \"opens java.lang\" to unnamed module @3b95a09c</code></pre>\n<p>Since Java 9, modules enforce <strong>strong encapsulation</strong>: a package is reachable by reflection only if its module <code>opens</code> it. Code in your own application is on the classpath, in the unnamed module, and open to itself, so the example above with <code>Invoice</code> works. The JDK's internals are closed, and since JDK 17 the old escape flag <code>--illegal-access</code> is gone. You can still grant access explicitly on the command line, <code>--add-opens java.base/java.lang=ALL-UNNAMED</code>, which is what you will see in the startup scripts of older frameworks. Treat each such flag as technical debt: it is a statement that a library depends on JDK internals.</p>\n<p>What about <code>final</code> fields? <code>Field.set</code> on a final instance field works after <code>setAccessible(true)</code> for ordinary classes, though it is a bad idea: the JIT may have inlined the old value, and the behaviour is formally undefined. It does not work on <code>static final</code> fields or on record and hidden class fields. The platform is moving to make <code>final</code> mean final, with warnings first, under JEP 500; do not build on it.</p>\n<h2>Invoking methods</h2>\n<p>A <code>Method</code> can be called on an instance with <code>invoke</code>. The first argument is the target (or <code>null</code> for static methods), followed by the arguments:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/MethodInvoke.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.math.BigDecimal;\n\npublic class MethodInvoke {\n    public static void main(String[] args) throws Exception {\n        var invoice = new Inspect.Invoice(7L, new BigDecimal(\"100.00\"));\n\n        Method discount = Inspect.Invoice.class.getDeclaredMethod(\"applyDiscount\", int.class);\n        discount.setAccessible(true);\n        discount.invoke(invoice, 20);                     // boxes 20 to Integer, unboxes inside\n        System.out.println(invoice.total());              // 80.0000\n\n        Method parse = Integer.class.getMethod(\"parseInt\", String.class);\n        Object result = parse.invoke(null, \"42\");         // static: no target\n        System.out.println(result);                       // 42\n\n        try {\n            parse.invoke(null, \"forty-two\");\n        } catch (InvocationTargetException e) {\n            System.out.println(\"method threw: \" + e.getCause());\n        }\n    }\n}</code></pre>\n<pre><code class=\"language-text\">80.0000\n42\nmethod threw: java.lang.NumberFormatException: For input string: \"forty-two\"</code></pre>\n<p>Three details trip people up. First, the parameter types are part of the lookup: <code>getDeclaredMethod(\"applyDiscount\", int.class)</code> finds the method taking a primitive <code>int</code>, while <code>Integer.class</code> would throw <code>NoSuchMethodException</code>. Second, <strong>an exception thrown by the invoked method is wrapped</strong> in <code>InvocationTargetException</code>; the real cause is <code>e.getCause()</code>. A framework that fails to unwrap it reports \"InvocationTargetException\" in the log, which tells you nothing, and the actual error is in the nested \"Caused by\". Third, arguments and results are boxed, <code>Object</code> all the way, and a wrong argument count or type produces <code>IllegalArgumentException: wrong number of arguments</code> or <code>argument type mismatch</code> at run time.</p>\n<p>Always unwrap in your own code:</p>\n<pre><code class=\"language-java\">static Object call(Method m, Object target, Object... args) throws Throwable {\n    try {\n        return m.invoke(target, args);\n    } catch (InvocationTargetException e) {\n        throw e.getCause();       // rethrow the real failure, not the wrapper\n    }\n}</code></pre>\n<h2>Creating instances</h2>\n<p>For a no-argument constructor, <code>getDeclaredConstructor().newInstance()</code>; for others, pass the parameter types and then the arguments. The older <code>Class.newInstance()</code> is deprecated because it propagated checked exceptions without declaring them:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/Create.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.Constructor;\nimport java.math.BigDecimal;\n\npublic class Create {\n    public static &lt;T&gt; T create(Class&lt;T&gt; type, Class&lt;?&gt;[] types, Object... args) throws ReflectiveOperationException {\n        Constructor&lt;T&gt; ctor = type.getDeclaredConstructor(types);\n        ctor.setAccessible(true);\n        return ctor.newInstance(args);\n    }\n\n    public static void main(String[] args) throws Exception {\n        Inspect.Invoice invoice = create(Inspect.Invoice.class,\n                new Class&lt;?&gt;[]{long.class, BigDecimal.class}, 9L, new BigDecimal(\"55.00\"));\n        System.out.println(invoice.total());     // 55.00\n\n        // plugin style: the class name comes from configuration\n        String implementation = \"java.util.ArrayDeque\";\n        Object queue = Class.forName(implementation).getDeclaredConstructor().newInstance();\n        System.out.println(queue.getClass().getSimpleName());\n    }\n}</code></pre>\n<p><code>ReflectiveOperationException</code> is the common parent of <code>ClassNotFoundException</code>, <code>NoSuchMethodException</code>, <code>IllegalAccessException</code>, <code>InstantiationException</code> and <code>InvocationTargetException</code>, so one catch covers the family. The plugin style in the last lines is the classic use: a configuration file names a class, and the program instantiates it. For that case, the JDK has a better tool than hand-written <code>forName</code>, <code>ServiceLoader</code>, which finds implementations declared in <code>META-INF/services</code> or a module descriptor and instantiates them for you, with type safety and no strings in code:</p>\n<pre><code class=\"language-java\">for (PaymentPlugin plugin : ServiceLoader.load(PaymentPlugin.class)) {\n    registry.register(plugin);\n}</code></pre>\n<p>Use <code>ServiceLoader</code> for plugin discovery and reserve <code>Class.forName</code> for the cases where the name truly comes from outside.</p>\n<h2>Records, enums and sealed types</h2>\n<p>Modern Java features have reflective support, and a mapper written today should use it. A record exposes its components in declaration order, which is exactly what a serializer needs:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/RecordToMap.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.RecordComponent;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\npublic class RecordToMap {\n\n    record Customer(long id, String name, boolean active) {}\n\n    public static Map&lt;String, Object&gt; toMap(Record record) throws ReflectiveOperationException {\n        Map&lt;String, Object&gt; out = new LinkedHashMap&lt;&gt;();\n        for (RecordComponent c : record.getClass().getRecordComponents()) {\n            out.put(c.getName(), c.getAccessor().invoke(record));     // call the accessor, not the field\n        }\n        return out;\n    }\n\n    public static &lt;T extends Record&gt; T fromMap(Class&lt;T&gt; type, Map&lt;String, Object&gt; values) throws ReflectiveOperationException {\n        RecordComponent[] components = type.getRecordComponents();\n        Class&lt;?&gt;[] types = new Class&lt;?&gt;[components.length];\n        Object[] args = new Object[components.length];\n        for (int i = 0; i &lt; components.length; i++) {\n            types[i] = components[i].getType();\n            args[i] = values.get(components[i].getName());\n        }\n        return type.getDeclaredConstructor(types).newInstance(args);   // canonical constructor\n    }\n\n    public static void main(String[] args) throws Exception {\n        var map = toMap(new Customer(1L, \"Ana\", true));\n        System.out.println(map);\n        System.out.println(fromMap(Customer.class, map));\n    }\n}</code></pre>\n<pre><code class=\"language-text\">{id=1, name=Ana, active=true}\nCustomer[id=1, name=Ana, active=true]</code></pre>\n<p>Going through the accessor and the canonical constructor respects the record's own validation, which writing to its fields would bypass. Enums offer <code>getEnumConstants()</code>, and a sealed interface lists its subtypes with <code>getPermittedSubclasses()</code>, which lets a serializer or a visitor generator find every case at run time, a capability that did not exist for open class hierarchies.</p>\n<h2>Dynamic proxies</h2>\n<p>A <strong>dynamic proxy</strong> is an object created at run time that implements one or more interfaces and sends every call to an <code>InvocationHandler</code>. It is the foundation of declarative features: transactions, caching, retries, security checks and mock libraries all wrap a real object in a proxy that adds behaviour around each call.</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/TimingProxy.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Proxy;\n\npublic class TimingProxy {\n\n    public interface Calculator {\n        int slowAdd(int a, int b);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public static &lt;T&gt; T timed(Class&lt;T&gt; iface, T target) {\n        return (T) Proxy.newProxyInstance(\n                iface.getClassLoader(),\n                new Class&lt;?&gt;[]{iface},\n                (proxy, method, args) -&gt; {\n                    long start = System.nanoTime();\n                    try {\n                        return method.invoke(target, args);\n                    } catch (InvocationTargetException e) {\n                        throw e.getCause();\n                    } finally {\n                        System.out.printf(\"%s took %d us%n\", method.getName(), (System.nanoTime() - start) / 1_000);\n                    }\n                });\n    }\n\n    public static void main(String[] args) {\n        Calculator real = (a, b) -&gt; {\n            try { Thread.sleep(20); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n            return a + b;\n        };\n        Calculator calc = timed(Calculator.class, real);\n\n        System.out.println(calc.slowAdd(2, 3));\n    }\n}</code></pre>\n<pre><code class=\"language-text\">slowAdd took 20431 us\n5</code></pre>\n<p>The microsecond figure will differ on your machine. The pattern is the point: the caller sees a <code>Calculator</code>, the handler sees every call with the <code>Method</code> and its arguments, and the real object is untouched. Two limits matter. The JDK proxy works <strong>only for interfaces</strong>. Spring and others use CGLIB or ByteBuddy to subclass concrete classes, with the extra rule that the class and the methods cannot be <code>final</code>, which is why <code>@Transactional</code> on a <code>final</code> method silently does nothing. And <strong>self invocation bypasses the proxy</strong>: when a method of the target calls another of its own methods, it does so on <code>this</code>, the real object, not on the proxy, so the added behaviour does not run. The second point causes a steady stream of \"why is this <code>@Transactional</code> method not transactional\" questions; the full treatment is in <a href=\"/library/spring-aop-logging-aspect-write\">Spring AOP proxies and how they intercept calls</a>.</p>\n<h2>A small dependency injection container</h2>\n<p>Putting annotations and reflection together shows how a framework works. This container reads an <code>@Inject</code> annotation on a constructor, creates the dependencies first and caches singletons:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/MiniContainer.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.annotation.*;\nimport java.lang.reflect.Constructor;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MiniContainer {\n\n    @Retention(RetentionPolicy.RUNTIME)\n    @Target(ElementType.CONSTRUCTOR)\n    public @interface Inject {}\n\n    private final Map&lt;Class&lt;?&gt;, Object&gt; singletons = new HashMap&lt;&gt;();\n    private final Map&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt; bindings = new HashMap&lt;&gt;();\n\n    public &lt;T&gt; void bind(Class&lt;T&gt; type, Class&lt;? extends T&gt; implementation) {\n        bindings.put(type, implementation);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public &lt;T&gt; T get(Class&lt;T&gt; type) {\n        Object existing = singletons.get(type);\n        if (existing != null) {\n            return (T) existing;\n        }\n        Class&lt;?&gt; concrete = bindings.getOrDefault(type, type);\n        try {\n            Constructor&lt;?&gt; ctor = injectConstructor(concrete);\n            Class&lt;?&gt;[] params = ctor.getParameterTypes();\n            Object[] args = new Object[params.length];\n            for (int i = 0; i &lt; params.length; i++) {\n                args[i] = get(params[i]);              // recursion resolves the graph\n            }\n            Object instance = ctor.newInstance(args);\n            singletons.put(type, instance);\n            return (T) instance;\n        } catch (ReflectiveOperationException e) {\n            throw new IllegalStateException(\"cannot create \" + type.getName(), e);\n        }\n    }\n\n    private Constructor&lt;?&gt; injectConstructor(Class&lt;?&gt; type) throws NoSuchMethodException {\n        for (Constructor&lt;?&gt; c : type.getDeclaredConstructors()) {\n            if (c.isAnnotationPresent(Inject.class)) {\n                return c;\n            }\n        }\n        return type.getDeclaredConstructor();          // fall back to the no-argument constructor\n    }\n}</code></pre>\n<pre><code class=\"language-java\">interface Clock2 { long now(); }\nclass SystemClock2 implements Clock2 { public long now() { return System.currentTimeMillis(); } }\nclass Billing {\n    private final Clock2 clock;\n    @MiniContainer.Inject Billing(Clock2 clock) { this.clock = clock; }\n    String stamp() { return \"billed at \" + clock.now(); }\n}\n\nvar container = new MiniContainer();\ncontainer.bind(Clock2.class, SystemClock2.class);\nSystem.out.println(container.get(Billing.class).stamp());</code></pre>\n<p>Under fifty lines, and it demonstrates everything that makes Spring work: finding the constructor by annotation, reading its parameter types, recursively creating those, caching. What it lacks shows why the real thing is bigger: cycle detection (two classes needing each other would recurse until <code>StackOverflowError</code>), scopes, <code>@Qualifier</code>, lifecycle callbacks and proxies. The point is that the framework is a program, not a mystery, and a missing bean error is a lookup that failed. A look at the real mechanism is in <a href=\"/library/spring-container-works-really\">how the Spring container really works</a>.</p>\n<h2>Method handles: the modern alternative</h2>\n<p><code>java.lang.invoke.MethodHandle</code>, added in Java 7, is a typed reference to a method that the JIT can optimise like a direct call when the handle is held in a constant. It does its access check once, at lookup, not at every call, and it has a clean model for security: you can only look up what the <code>Lookup</code> object you hold has access to.</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/Handles.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.invoke.MethodHandle;\nimport java.lang.invoke.MethodHandles;\nimport java.lang.invoke.MethodType;\n\npublic class Handles {\n\n    private static final MethodHandle UPPER;\n\n    static {\n        try {\n            UPPER = MethodHandles.lookup()\n                    .findVirtual(String.class, \"toUpperCase\", MethodType.methodType(String.class));\n        } catch (ReflectiveOperationException e) {\n            throw new ExceptionInInitializerError(e);\n        }\n    }\n\n    public static void main(String[] args) throws Throwable {\n        String result = (String) UPPER.invokeExact(\"hello\");    // exact signature, no boxing\n        System.out.println(result);                              // HELLO\n\n        MethodHandle bound = UPPER.bindTo(\"bound value\");\n        System.out.println((String) bound.invoke());             // BOUND VALUE\n    }\n}</code></pre>\n<p><code>invokeExact</code> requires the call site's static types to match the handle's type exactly, here <code>(String)String</code>, and fails with <code>WrongMethodTypeException</code> otherwise; <code>invoke</code> adapts the types at some cost. Handles can be composed, with <code>bindTo</code>, <code>filterArguments</code>, <code>guardWithTest</code>, which is how lambdas and string concatenation are linked on modern JVMs. Prefer a handle in a <code>static final</code> field: the JIT treats the handle as a constant only then. <code>VarHandle</code> is the equivalent for fields and arrays with atomic and memory ordering operations, replacing <code>Unsafe</code> for most uses. For application code the practical rule is: if you call the same reflective member many times, use a handle; for a one off call, plain reflection is fine.</p>\n<h2>Class loaders: why a Class is more than a name</h2>\n<p>The three ways of getting a <code>Class</code> hide a concept that explains many odd errors: a class is identified by its <strong>name together with the class loader</strong> that defined it. The JVM has a hierarchy of loaders. The bootstrap loader loads the core <code>java.base</code> module, the platform loader loads the other JDK modules and the application loader loads your classpath. Application servers and plugin systems add loaders of their own so that each deployed application has its own isolated copy of a library.</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/Loaders.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\npublic class Loaders {\n    public static void main(String[] args) {\n        System.out.println(String.class.getClassLoader());              // null: the bootstrap loader\n        System.out.println(java.sql.Connection.class.getClassLoader()); // platform loader\n        System.out.println(Loaders.class.getClassLoader());             // the application loader\n\n        ClassLoader loader = Loaders.class.getClassLoader();\n        while (loader != null) {\n            System.out.println(\"parent chain: \" + loader.getName());\n            loader = loader.getParent();\n        }\n    }\n}</code></pre>\n<pre><code class=\"language-text\">null\njdk.internal.loader.ClassLoaders$PlatformClassLoader@5ca881b5\njdk.internal.loader.ClassLoaders$AppClassLoader@2c13da15\nparent chain: app\nparent chain: platform</code></pre>\n<p>The <code>null</code> for <code>String</code> is not a bug: the bootstrap loader has no Java object to print. Loading is <strong>delegated upwards</strong>: a loader asks its parent first and only defines the class itself if the parents cannot, which is why you cannot replace <code>java.lang.String</code> by putting your own copy on the classpath. The consequences for reflection are practical. <code>Class.forName(\"x.Y\")</code> uses the loader of the calling class, which can miss classes visible only to another loader, and the fix in frameworks is to use the thread context class loader, <code>Thread.currentThread().getContextClassLoader()</code>, which a container sets to the loader of the application being served. Two copies of the same class in two loaders are different types, so passing an object across the boundary gives <code>ClassCastException: class dev.javahacks.Order cannot be cast to class dev.javahacks.Order (dev.javahacks.Order is in unnamed module of loader 'app'; dev.javahacks.Order is in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader)</code>. The message names both loaders, and reading them is the whole diagnosis: the class exists twice, so one of the two copies must be removed from the deployment.</p>\n<h2>Reading generic signatures</h2>\n<p>Section after section above worked with raw <code>Class</code> objects, which erase generics. The reflective API still exposes the declared generic types, as the erasure post explained, through the <code>getGeneric...</code> methods and the <code>java.lang.reflect.Type</code> hierarchy. This is how a mapper learns that a field is a <code>List&lt;Order&gt;</code> and not a bare <code>List</code>:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/GenericSignatures.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.*;\nimport java.util.List;\nimport java.util.Map;\n\npublic class GenericSignatures {\n\n    static class Catalog {\n        Map&lt;String, List&lt;Integer&gt;&gt; prices;\n        List&lt;? extends Number&gt; readings;\n\n        &lt;T extends Comparable&lt;T&gt;&gt; T max(List&lt;T&gt; values) { return values.get(0); }\n    }\n\n    static String describe(Type t) {\n        if (t instanceof Class&lt;?&gt; c) {\n            return c.getSimpleName();\n        }\n        if (t instanceof ParameterizedType p) {\n            var args = java.util.Arrays.stream(p.getActualTypeArguments()).map(GenericSignatures::describe).toList();\n            return ((Class&lt;?&gt;) p.getRawType()).getSimpleName() + args;\n        }\n        if (t instanceof WildcardType w) {\n            return \"? extends \" + java.util.Arrays.stream(w.getUpperBounds()).map(GenericSignatures::describe).toList();\n        }\n        if (t instanceof TypeVariable&lt;?&gt; v) {\n            return \"type variable \" + v.getName() + \" extends \" + java.util.Arrays.stream(v.getBounds()).map(GenericSignatures::describe).toList();\n        }\n        return t.getTypeName();\n    }\n\n    public static void main(String[] args) throws Exception {\n        for (Field f : Catalog.class.getDeclaredFields()) {\n            System.out.println(f.getName() + \": \" + describe(f.getGenericType()));\n        }\n        Method max = Catalog.class.getDeclaredMethod(\"max\", List.class);\n        System.out.println(\"returns \" + describe(max.getGenericReturnType()));\n    }\n}</code></pre>\n<pre><code class=\"language-text\">prices: Map[String, List[Integer]]\nreadings: List[? extends [Number]]\nreturns type variable T extends [Comparable[T]]</code></pre>\n<p>A <code>Type</code> is a small tree: a <code>Class</code> for a plain type, a <code>ParameterizedType</code> for <code>List&lt;Order&gt;</code>, a <code>WildcardType</code> for <code>? extends Number</code>, a <code>TypeVariable</code> for <code>T</code> and a <code>GenericArrayType</code> for <code>T[]</code>. Real mappers recurse through exactly this structure. The one thing you cannot read is the type argument of a *local variable* or of a *particular instance*, since neither is part of the class file. That is the case the super type token covers, and it is why <code>new TypeReference&lt;List&lt;Order&gt;&gt;() {}</code> exists in Jackson.</p>\n<h2>Modules: opening your own packages</h2>\n<p>On the module path, your own code is not open to reflection by default either. A modular application that Jackson must serialise has to say so in its descriptor:</p>\n<pre data-filename=\"src/main/java/module-info.java\"><code class=\"language-java\">module dev.javahacks.orders {\n    requires com.fasterxml.jackson.databind;\n    requires jakarta.persistence;\n\n    exports dev.javahacks.orders.api;                                   // compile time access for everyone\n    opens dev.javahacks.orders.model to com.fasterxml.jackson.databind, org.hibernate.orm.core;\n}</code></pre>\n<p>The distinction between the two keywords is the point. <code>exports</code> lets other modules compile against public types, while <code>opens</code> lets them use deep reflection on every member, private ones included, at run time. A qualified <code>opens ... to</code> grants the right only to named modules, which is the least privilege version. Forgetting it produces an error that mentions the module by name, the same <code>InaccessibleObjectException</code> as before, this time about your own package. Most Spring Boot applications run on the classpath, where the whole application is in the unnamed module and everything is open, which is why the issue is invisible until the first modularisation.</p>\n<h2>How the frameworks you use rely on it</h2>\n<p>It is useful to know which reflective feature each well known library depends on, because their errors then make sense.</p>\n<table><thead><tr><th>Library</th><th>What it does with reflection</th><th>What goes wrong</th></tr></thead><tbody><tr><td>JUnit</td><td>Scans for methods annotated <code>@Test</code>, creates the test class by constructor, invokes lifecycle methods</td><td><code>@Test</code> method not found if it is <code>private</code> or has parameters it cannot resolve</td></tr><tr><td>Spring</td><td>Scans for stereotype annotations, calls constructors with resolved dependencies, wraps beans in proxies</td><td><code>NoSuchBeanDefinitionException</code>, <code>final</code> methods not proxied, self invocation skipping advice</td></tr><tr><td>Jackson</td><td>Reads constructors, record components, getters and annotated fields, writes through setters or fields</td><td><code>InvalidDefinitionException: No suitable constructor</code> when no creator can be found; modules not opened</td></tr><tr><td>Hibernate</td><td>Instantiates entities through a no-argument constructor, reads and writes fields, builds proxies for lazy loading</td><td><code>final</code> entity classes cannot be proxied; missing default constructor</td></tr><tr><td>Mockito</td><td>Creates subclasses or inline mocks of classes at run time and intercepts every call</td><td><code>Cannot mock/spy class ... final class</code> on older versions without the inline mock maker</td></tr></tbody></table>\n<p>The recurring theme in the last column is that each failure is a limit of reflection or proxying stated in the library's own words, which the sections above prepared you to read: a class that is <code>final</code> cannot be subclassed, an inaccessible member needs permission, a constructor must be found by exact parameter types.</p>\n<h2>Debugging reflective code</h2>\n<p>Reflective bugs are hard because the stack trace shows framework internals instead of your call. A short routine finds the cause.</p>\n<p>Read the *innermost* \"Caused by\" first, since reflection wraps everything: an <code>InvocationTargetException</code> or a framework wrapper such as <code>BeanInstantiationException</code> carries the real exception as the cause, and the first line of the trace is almost never the one that matters. Then identify which of the table's exceptions you have and work from its row. For <code>NoSuchMethodException</code>, print what the class really declares, with the inspector from earlier, because the usual cause is a signature that differs by a boxed type or by a parameter you forgot. For a missing class, print <code>Thread.currentThread().getContextClassLoader()</code> and the resource URL of the class file with <code>getResource(\"/dev/javahacks/Order.class\")</code>, which shows which jar it came from or that it came from nowhere. And when behaviour is wrong rather than failing, turn the reflective call into a log line that records the class, member and arguments, because the stack trace alone does not tell you which of a hundred reflective calls misbehaved.</p>\n<pre><code class=\"language-java\">static Object invokeLogged(Method m, Object target, Object... args) throws Throwable {\n    System.out.printf(\"invoke %s#%s(%s) on %s%n\", m.getDeclaringClass().getSimpleName(), m.getName(),\n            java.util.Arrays.toString(args), target);\n    return call(m, target, args);\n}</code></pre>\n<p>A tool worth knowing for the performance side is Java Flight Recorder: it records method samples, and a reflective hot spot shows up under <code>jdk.internal.reflect</code> or <code>java.lang.invoke</code> frames, which tells you the cost really is in reflection before you rewrite anything.</p>\n<h2>What reflection costs</h2>\n<p>The cost has four parts, and only the first is speed.</p>\n<p><strong>Call overhead.</strong> A reflective <code>Method.invoke</code> boxes arguments, checks access and dispatches through a handle or accessor, where a direct call is inlined by the JIT. Since Java 18, core reflection is implemented with method handles under the covers, which narrowed the gap, but a direct call is still cheaper and a constant <code>MethodHandle</code> is the closest to it. Do not trust a number from an article for your workload; write a JMH benchmark (<a href=\"/library/jmh-microbenchmark-write-correct\">how to benchmark correctly with JMH</a>) and compare. A mapper that reflects once per class at startup and caches the <code>Method</code> and <code>Field</code> objects is fast enough for almost everything. Calling <code>getDeclaredMethods()</code> on every request is the mistake, because each call copies the array.</p>\n<p><strong>Late failure.</strong> A misspelled method name compiles and fails at run time, maybe in production on a rare branch. Add startup checks that resolve every reflective lookup eagerly, so errors appear when the application boots.</p>\n<p><strong>Hidden coupling.</strong> Renaming a method no longer fails the build when some string elsewhere refers to it, and IDE refactoring tools may not see the reference. Reflection breaks \"find usages\".</p>\n<p><strong>Platform friction.</strong> Strong encapsulation, native image and obfuscators all need to be told what reflection touches.</p>\n<h2>Native image and reflection metadata</h2>\n<p>A GraalVM native image is built by a closed world analysis: it keeps only code it can prove is reachable. A string passed to <code>Class.forName</code> defeats the analysis, so reflective access to a class must be declared in advance, in a JSON file under <code>META-INF/native-image</code>:</p>\n<pre data-filename=\"src/main/resources/META-INF/native-image/dev.javahacks/orders/reachability-metadata.json\"><code class=\"language-json\">{\n  \"reflection\": [\n    {\n      \"type\": \"dev.javahacks.orders.Customer\",\n      \"allDeclaredConstructors\": true,\n      \"allDeclaredFields\": true,\n      \"allPublicMethods\": true\n    }\n  ]\n}</code></pre>\n<p>Frameworks cope by generating this metadata at build time: Spring's AOT processing and Quarkus's build steps both replace run time classpath scanning with generated code, which is also why they start faster. If you write a library that uses reflection and want it to work in native image, document the types it needs and ship the metadata. The same problem, in another guise, is why Quarkus and Micronaut avoid reflection by design.</p>\n<h2>Caching reflective metadata</h2>\n<p>The performance advice above has a concrete form. Look a class up once, build whatever structure you need and keep it. The cheapest correct design is a small cache keyed by <code>Class</code>, filled lazily and safely shared between threads:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/MappingCache.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ClassValue;\n\npublic final class MappingCache {\n\n    public record Column(String name, Field field) {}\n\n    private static final ClassValue&lt;List&lt;Column&gt;&gt; COLUMNS = new ClassValue&lt;&gt;() {\n        @Override\n        protected List&lt;Column&gt; computeValue(Class&lt;?&gt; type) {\n            List&lt;Column&gt; columns = new ArrayList&lt;&gt;();\n            for (Field f : type.getDeclaredFields()) {\n                if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) {\n                    continue;\n                }\n                f.setAccessible(true);                       // done once, not per call\n                columns.add(new Column(f.getName(), f));\n            }\n            return List.copyOf(columns);\n        }\n    };\n\n    public static List&lt;Column&gt; columnsOf(Class&lt;?&gt; type) {\n        return COLUMNS.get(type);\n    }\n}</code></pre>\n<p><code>ClassValue</code> is the JDK's purpose built per class cache: it computes the value once per class, is thread safe, and, unlike a static <code>Map&lt;Class&lt;?&gt;, ...&gt;</code>, does not keep the class alive after its class loader is discarded, which prevents the class loader leak that a naive static map causes in an application server. That last point is a real production failure: a <code>ConcurrentHashMap&lt;Class&lt;?&gt;, X&gt;</code> held by a library jar loaded in a shared parent loader pins every web application's classes in memory across redeploys, and the symptom is <code>OutOfMemoryError: Metaspace</code> after the fifth deployment.</p>\n<h2>Building a small annotation driven mapper</h2>\n<p>Reflection, annotations and the cache combine into the thing most applications use reflection for, mapping an object to named values. This mapper writes any object's annotated fields into a map, which could be a SQL parameter source or a JSON tree. The annotation controls naming and exclusion:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/Mapped.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.annotation.*;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.FIELD)\npublic @interface Mapped {\n    String name() default \"\";\n    boolean skip() default false;\n}</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/reflect/ObjectMapper2.java\"><code class=\"language-java\">package dev.javahacks.reflect;\n\nimport java.lang.reflect.Field;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\npublic final class ObjectMapper2 {\n\n    public static Map&lt;String, Object&gt; toMap(Object source) {\n        Map&lt;String, Object&gt; out = new LinkedHashMap&lt;&gt;();\n        for (MappingCache.Column column : MappingCache.columnsOf(source.getClass())) {\n            Field field = column.field();\n            Mapped rule = field.getAnnotation(Mapped.class);\n            if (rule != null &amp;&amp; rule.skip()) {\n                continue;\n            }\n            String key = (rule == null || rule.name().isEmpty()) ? column.name() : rule.name();\n            try {\n                out.put(key, field.get(source));\n            } catch (IllegalAccessException e) {\n                throw new IllegalStateException(\"cannot read \" + field, e);\n            }\n        }\n        return out;\n    }\n}</code></pre>\n<pre><code class=\"language-java\">class Account {\n    @Mapped(name = \"account_id\") long id = 7;\n    String owner = \"Ana\";\n    @Mapped(skip = true) String password = \"secret\";\n}\n\nSystem.out.println(ObjectMapper2.toMap(new Account()));</code></pre>\n<pre><code class=\"language-text\">{account_id=7, owner=Ana}</code></pre>\n<p>Run through the design choices. The cache does the reflective lookup and the <code>setAccessible</code> call once per class. Static fields are skipped because they belong to the type, not the instance. The annotation overrides the name and can exclude a secret. A failure to read turns into an <code>IllegalStateException</code> carrying the field that failed, so the message is useful. A production mapper adds type conversion, nested objects, collections and inheritance, and each of those is another few dozen lines, which is the honest measure of why people use Jackson instead of writing this. The exercise is still valuable: when you have written the simplified version, the configuration options of the real one become obvious.</p>\n<h2>Gotchas in method lookup</h2>\n<p>Some behaviours of <code>getMethod</code> and <code>invoke</code> surprise even experienced developers.</p>\n<p><strong>Overloads.</strong> <code>getMethod(\"add\", Integer.class)</code> and <code>getMethod(\"add\", int.class)</code> find different methods. <code>invoke</code> does not do overload resolution for you: you pick the exact signature, and the runtime does not choose the \"closest\" match the way the compiler does. A framework that supports overloaded methods must implement its own matching.</p>\n<p><strong>Bridge and synthetic methods.</strong> The compiler adds bridge methods for generics and covariant returns, so <code>getDeclaredMethods()</code> may list the same logical method twice: once with the specific return type and once with <code>Object</code>. Filter with <code>method.isBridge()</code> and <code>method.isSynthetic()</code> when you scan for annotated methods, or you will register a handler twice.</p>\n<p><strong>Varargs.</strong> A method declared <code>log(String format, Object... args)</code> takes an <code>Object[]</code> as its last parameter when found reflectively, so you must pass the array yourself: <code>m.invoke(target, \"x={}\", new Object[]{1})</code>. Passing the values loose gives <code>IllegalArgumentException: wrong number of arguments</code>.</p>\n<p><strong>Inherited and interface methods.</strong> A method declared on an interface and implemented in a class can be invoked through either <code>Method</code> object. If the implementing class is not public, using the class's own <code>Method</code> fails with <code>IllegalAccessException</code> even for a public method, while the interface's <code>Method</code> works. When invoking public API reflectively, resolve the method on the public type, not the private implementation.</p>\n<p><strong>Default methods.</strong> An interface <code>default</code> method is found with <code>getMethod</code> on the implementing class and invoked normally, but a dynamic proxy that wants to call a default method of its own interface needs <code>InvocationHandler.invokeDefault</code>, available since Java 16.</p>\n<p>**Static members and <code>null</code>.** For a static field or method, the target argument is ignored, and passing a real instance does no harm, which is how code written for instance members tends to survive being pointed at a static one.</p>\n<h2>Common exceptions, decoded</h2>\n<table><thead><tr><th>Exception</th><th>What it means</th><th>Usual cause</th></tr></thead><tbody><tr><td><code>ClassNotFoundException</code></td><td><code>forName</code> could not find the class</td><td>Typo, missing dependency, wrong class loader</td></tr><tr><td><code>NoSuchMethodException</code></td><td>No method with that name and parameter types</td><td>Boxed vs primitive type, wrong declaring class, inherited method looked up with <code>getDeclared...</code></td></tr><tr><td><code>NoSuchFieldException</code></td><td>No such field in this class</td><td>Field is in a superclass</td></tr><tr><td><code>IllegalAccessException</code></td><td>Member not accessible</td><td>Missing <code>setAccessible(true)</code>, or a non-public class in another package</td></tr><tr><td><code>InaccessibleObjectException</code></td><td>Module does not open the package</td><td>JDK internals; add <code>--add-opens</code> or stop using them</td></tr><tr><td><code>InvocationTargetException</code></td><td>The invoked method threw</td><td>Read <code>getCause()</code></td></tr><tr><td><code>IllegalArgumentException: argument type mismatch</code></td><td>Wrong argument for <code>invoke</code></td><td>Passing <code>Integer</code> where <code>long</code> is required</td></tr><tr><td><code>InstantiationException</code></td><td>Class is abstract or an interface</td><td>Instantiating the wrong type</td></tr><tr><td><code>ExceptionInInitializerError</code></td><td>A static initialiser threw</td><td>Look at the nested cause</td></tr></tbody></table>\n<p>Keep this table near a debugging session. Almost all reflective bugs are in the first four rows.</p>\n<h2>A security note</h2>\n<p>Reflection is a power tool aimed at your own program, and becomes a weapon when the strings come from outside. <code>Class.forName(request.getParameter(\"class\"))</code> followed by <code>newInstance</code> lets a caller instantiate any class on the classpath, including ones with dangerous constructors. Never use untrusted input as a class or method name. If you must map input to behaviour, use an allow list: a <code>Map&lt;String, Supplier&lt;Handler&gt;&gt;</code> keyed by a short name that you control. This is the same lesson as in <a href=\"/library/java-serialization-risks-safer-alternatives\">Java serialization risks</a>, where the stream names the classes. The <code>SecurityManager</code>, which once restricted reflection, was removed in Java 24, so no run time policy now constrains it within a process; the controls are the module system and your own discipline.</p>\n<h2>Testing code that uses reflection</h2>\n<p>Test the contract, not the mechanism. For a mapper, assert on the round trip of a record with several field types, a null, a nested record and a collection. For a container, assert on the graph it builds and on the error for a missing binding and for a cycle. For a proxy, assert that the wrapped call returns the real result, that exceptions are unwrapped and that the cross cutting behaviour ran once per call.</p>\n<pre><code class=\"language-java\">@Test\nvoid proxyUnwrapsTheRealException() {\n    Calculator failing = (a, b) -&gt; { throw new IllegalStateException(\"overflow\"); };\n    Calculator proxied = TimingProxy.timed(Calculator.class, failing);\n\n    assertThatThrownBy(() -&gt; proxied.slowAdd(1, 2))\n            .isInstanceOf(IllegalStateException.class)\n            .hasMessage(\"overflow\");\n}</code></pre>\n<p>Avoid using reflection in tests to reach private members of the class under test. That is a signal the class has a part that deserves its own, testable, package visible shape. Spring's <code>ReflectionTestUtils</code> exists and is useful for injecting a mock into a field of a legacy class, but a constructor is the better seam.</p>\n<h2>When not to use reflection</h2>\n<p>Reflection belongs in infrastructure: containers, mappers, test frameworks, serialisation libraries. In application logic it is almost always the wrong tool. A decision table:</p>\n<table><thead><tr><th>You want to</th><th>Reach for</th><th>Instead of reflection because</th></tr></thead><tbody><tr><td>Choose behaviour by type or key</td><td>An interface, a <code>Map&lt;String, Strategy&gt;</code> or an enum with methods</td><td>The compiler checks it</td></tr><tr><td>Call something passed in by the caller</td><td>A lambda or functional interface</td><td>Zero ceremony and inlinable</td></tr><tr><td>Find implementations of a service</td><td><code>ServiceLoader</code></td><td>Standard, module aware</td></tr><tr><td>Generate boilerplate such as builders or mappers</td><td>An annotation processor or a build plugin</td><td>Fails at compile time, no run time cost</td></tr><tr><td>Work with a closed set of subtypes</td><td>Sealed interfaces and pattern matching</td><td>Exhaustiveness checks</td></tr><tr><td>Call the same member repeatedly and fast</td><td><code>MethodHandle</code> in a <code>static final</code></td><td>Near direct call speed</td></tr><tr><td>Read your own private state in a test</td><td>Package private access or a redesign</td><td>Tests stay refactorable</td></tr><tr><td>Copy fields between objects</td><td>A mapper generated at compile time</td><td>Faster and refactor safe</td></tr></tbody></table>\n<p>A good sign you have reached for reflection too soon is a growing pile of strings naming members. If you can imagine the same code with an interface and one extra class, write that.</p>\n<h2>A refactoring: from reflective dispatch to a registry</h2>\n<p>The most common misuse of reflection in application code is dispatching by name. A report generator receives a string such as <code>\"sales\"</code> from a request and finds the method to run by building its name:</p>\n<pre><code class=\"language-java\">public String generate(String kind) throws Exception {\n    Method m = ReportService.class.getDeclaredMethod(\"generate\" + capitalize(kind));\n    return (String) m.invoke(this);\n}</code></pre>\n<p>It works, and every property listed earlier goes wrong at once. A request with <code>kind=admin</code> reaches <code>generateAdmin</code>, a method nobody meant to expose, because the string chooses the method. A rename of <code>generateSales</code> compiles and fails in production. The call cannot be found by \"find usages\", and every call pays reflective overhead. The cure takes one interface and one map, and it does what the reflective version did, only checked:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/reports/ReportRegistry.java\"><code class=\"language-java\">public interface Report {\n    String generate();\n}\n\n@Component\npublic class ReportRegistry {\n    private final Map&lt;String, Report&gt; reports;\n\n    public ReportRegistry(Map&lt;String, Report&gt; reportBeans) {      // Spring injects bean name -&gt; bean\n        this.reports = Map.copyOf(reportBeans);\n    }\n\n    public String generate(String kind) {\n        Report report = reports.get(kind);\n        if (report == null) {\n            throw new IllegalArgumentException(\"unknown report: \" + kind);\n        }\n        return report.generate();\n    }\n}</code></pre>\n<p>Each report is a small class annotated as a component, and the registry holds only what was registered, which is the allow list the security section recommended. The unknown key is a clear, immediate error. Adding a report means adding a class and nothing else, and the compiler verifies that every report implements <code>generate</code>. The conversion also shows when a framework's own reflection is the right tool: Spring uses reflection once, at startup, to find the beans and populate the map, and your code then runs on plain method calls. That division, reflection in the infrastructure and ordinary Java in the logic, is the arrangement to aim for.</p>\n<h2>A short checklist</h2>\n<p>Before writing reflective code, run through this list.</p>\n<ol><li>Can an interface, lambda, enum or sealed type express this? If yes, stop.</li><li>Are the names coming from trusted input? If not, use an allow list.</li><li>Are lookups done once and cached? <code>Method</code> and <code>Field</code> objects are reusable.</li><li>Is the failure path unwrapped, with <code>InvocationTargetException</code> replaced by its cause and a message naming the class and member?</li><li>Does startup resolve every reflective reference, so mistakes show at boot?</li><li>Does the code need <code>--add-opens</code>? If so, document the flag and the reason, and plan to remove it.</li><li>Does it need to run as a native image? Then provide metadata or generate code instead.</li><li>Is there a test for the contract and one for each failure mode in the table above?</li></ol>\n<h2>Where to go next</h2>\n<p>Reflection is the entry point to a family of related techniques, and the order in which they pay off is worth knowing. Start with annotations, because they let you move configuration out of strings and into the types themselves. Learn dynamic proxies next, since they explain declarative transactions, caching and retries in Spring, and the self invocation trap that goes with them. Method handles and <code>VarHandle</code> come after, when a measured hot spot justifies them. Annotation processors and build time code generation are the destination for anything performance or native image sensitive, because they do the reflective work once, at compile time, and leave plain code behind. Reading the source of a small library that uses these, such as a mapper or a test framework, is the quickest education, because the problems described above, unwrapping exceptions, caching lookups, handling bridge methods, appear in every one of them in the same form.</p>\n<h2>A closing rule of thumb</h2>\n<p>If you cannot explain in one sentence why this code must discover its types at run time, it probably should not. Reflection that serves a framework, a plugin boundary or a serialiser is doing the job it was made for. Reflection that dispatches on a string inside business logic is a design shortcut, and a registry or an interface will serve better.</p>\n<h2>When this does not apply</h2>\n<p>Not every program needs to know about reflection to be written well. A typical business application uses it indirectly, through frameworks, and writing it directly is a sign of building infrastructure. If you only need to read a few configuration values into a class, a framework's binding does it better than a hand rolled version. If your target is native image or a latency critical hot path, prefer generated code and method handles. For the primary sources, the [<code>java.lang.reflect</code> package documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/reflect/package-summary.html), the [<code>java.lang.invoke</code> package overview](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/invoke/package-summary.html), <a href=\"https://openjdk.org/jeps/403\">JEP 396 and 403 on strong encapsulation of JDK internals</a> and the <a href=\"https://www.graalvm.org/latest/reference-manual/native-image/metadata/\">GraalVM reachability metadata reference</a> are the documents to read.</p>","date_published":"2026-11-14T04:16:31+00:00","tags":["Java Core"]},{"id":"https://javahacks.dev/library/kafka-producer-configuration-configure-producers-durability","url":"https://javahacks.dev/library/kafka-producer-configuration-configure-producers-durability","title":"Kafka Producer Configuration for Durability in Java Services","summary":"A complete guide to Kafka producer durability in Java: acks, replication, idempotence, retries, transactions, the outbox, testing and monitoring.","content_html":"<p>A producer calls <code>send</code>, no exception is thrown, the application carries on and a week later a customer reports that an order never reached the shipping system. Nothing logged an error. This is the usual shape of message loss in Kafka systems: not a dramatic failure, but a default that favoured speed, a callback that nobody checked, or a database commit that succeeded while the message that was supposed to follow it did not. Kafka can be run so that an acknowledged message survives the loss of a broker, and Java producers can be configured and written so that failures are loud. It takes settings on the topic, settings on the producer and discipline in the code, and all three have to agree. This guide builds the full picture in order: how a write travels, what each setting guarantees, how to configure a plain Java producer and a Spring Boot one, how transactions and the outbox pattern keep a database and a topic consistent, how to test and monitor durability and what each failure scenario looks like. It assumes Kafka 3.x or 4.x clients, JDK 25 and Spring Boot 4 with Spring for Apache Kafka.</p>\n<p>The one sentence to keep: <strong>a message is durable only after the leader and enough followers have written it, and the producer has been told so and has checked.</strong> Every section below is a part of that sentence.</p>\n<h2>How a write travels through Kafka</h2>\n<p>A topic is split into partitions. Each partition has one <strong>leader</strong> broker and zero or more <strong>followers</strong> that copy the leader's log. A producer sends records for a partition to its leader. The leader appends them to its log, followers fetch and append, and the leader tracks which followers are caught up: the <strong>in-sync replicas</strong>, ISR. A record is <strong>committed</strong> once every replica in the ISR has it, and only committed records are visible to consumers. The producer's <code>acks</code> setting decides when the leader answers the producer.</p>\n<pre><code class=\"language-text\">producer --&gt; leader (append) --&gt; followers fetch and append\n                  |                          |\n                  +---- ISR = {leader, f1, f2} ----+\n                  |\n        acks=all: reply when every ISR member has the record</code></pre>\n<p>If the leader fails, the controller elects a new leader from the ISR. A follower outside the ISR may lack recent records, so promoting it would lose data; whether that is allowed is a topic setting we meet shortly. The durability question reduces to: what must be true when the producer is told \"success\" so that a leader crash cannot erase the record?</p>\n<h2>The topic: replication and min.insync.replicas</h2>\n<p>Durability starts where the topic is created. Two settings matter most:</p>\n<table><thead><tr><th>Setting</th><th>Meaning</th><th>Durable value</th></tr></thead><tbody><tr><td><code>replication.factor</code></td><td>How many copies of each partition</td><td>3</td></tr><tr><td><code>min.insync.replicas</code></td><td>The minimum ISR size for <code>acks=all</code> to succeed</td><td>2</td></tr><tr><td><code>unclean.leader.election.enable</code></td><td>Allow an out-of-sync replica to become leader</td><td>false</td></tr></tbody></table>\n<p>With a replication factor of 3 and <code>min.insync.replicas=2</code>, an <code>acks=all</code> write succeeds only when at least two replicas, the leader and one follower, have it. If one broker dies, two replicas remain, writes continue and no acknowledged record is lost. If two brokers are down, the ISR has one member, <code>min.insync.replicas</code> cannot be met and the leader rejects writes with <code>NotEnoughReplicasException</code>. That is the correct behaviour: the cluster refuses a write it cannot protect, trading availability for durability. Set <code>min.insync.replicas</code> equal to the replication factor and a single broker failure blocks writes; set it to 1 and <code>acks=all</code> degrades to the leader's word alone.</p>\n<p>Create the topic with these settings explicitly, in code, so they are versioned with the application:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/kafka/TopicConfig.java\"><code class=\"language-java\">@Configuration\npublic class TopicConfig {\n\n    @Bean\n    NewTopic orderEvents() {\n        return TopicBuilder.name(\"order-events\")\n                .partitions(12)\n                .replicas(3)\n                .config(TopicConfig.MIN_IN_SYNC_REPLICAS_CONFIG, \"2\")\n                .config(TopicConfig.UNCLEAN_LEADER_ELECTION_ENABLE_CONFIG, \"false\")\n                .config(TopicConfig.RETENTION_MS_CONFIG, String.valueOf(Duration.ofDays(7).toMillis()))\n                .build();\n    }\n}</code></pre>\n<p>Spring Boot's <code>KafkaAdmin</code> creates the topic at startup if it does not exist, and it does <strong>not</strong> change an existing topic, so a topic created earlier with defaults keeps them. Check what is in force on a real cluster with the command line tools:</p>\n<pre><code class=\"language-bash\">kafka-topics.sh --bootstrap-server broker:9092 --describe --topic order-events\nkafka-configs.sh --bootstrap-server broker:9092 --entity-type topics --entity-name order-events --describe</code></pre>\n<pre><code class=\"language-text\">Topic: order-events  TopicId: 5k2...  PartitionCount: 12  ReplicationFactor: 3  Configs: min.insync.replicas=2,unclean.leader.election.enable=false\n\tTopic: order-events  Partition: 0  Leader: 1  Replicas: 1,2,3  Isr: 1,2,3</code></pre>\n<p><code>Isr: 1,2,3</code> is healthy. A partition showing <code>Isr: 1</code> is under-replicated and one broker failure away from being unavailable. The cluster-wide defaults, set on brokers as <code>default.replication.factor=3</code> and <code>min.insync.replicas=2</code>, protect topics that someone creates without thinking; many managed offerings already set them.</p>\n<h2>The producer: acks</h2>\n<p><code>acks</code> is the producer's choice about whose word to take:</p>\n<table><thead><tr><th><code>acks</code></th><th>The producer waits for</th><th>Loss risk</th></tr></thead><tbody><tr><td><code>0</code></td><td>Nothing; fire and forget</td><td>Any network or broker problem loses data, with no signal</td></tr><tr><td><code>1</code></td><td>The leader's append</td><td>The leader crashes before followers copy: the acknowledged record is lost</td></tr><tr><td><code>all</code> (or <code>-1</code>)</td><td>The leader plus every in-sync replica (at least <code>min.insync.replicas</code>)</td><td>None for acknowledged records, if the topic is set up as above</td></tr></tbody></table>\n<p><code>acks=all</code> is the default since Kafka 3.0 (with idempotence), and you should set it explicitly anyway, because a configuration that states its intent survives version changes. The cost is latency: the write waits for a follower round trip. On a healthy cluster this is milliseconds, and it is the price of the guarantee.</p>\n<h2>Retries, timeouts and the delivery contract</h2>\n<p>Temporary failures are normal: a leader election, a network blip, a broker restart. The producer retries them for you, within a bounded time. Older advice tuned <code>retries</code> and <code>retry.backoff.ms</code> separately; the modern model is a <strong>delivery timeout</strong>: the total time from the call to <code>send</code> until the producer gives up.</p>\n<table><thead><tr><th>Setting</th><th>Default</th><th>Role</th></tr></thead><tbody><tr><td><code>delivery.timeout.ms</code></td><td>120000</td><td>Upper bound for send to success or failure, covering batching, retries and waiting</td></tr><tr><td><code>request.timeout.ms</code></td><td>30000</td><td>How long to wait for a single broker response</td></tr><tr><td><code>retries</code></td><td>2147483647</td><td>Effectively unlimited; the delivery timeout is what stops it</td></tr><tr><td><code>retry.backoff.ms</code></td><td>100</td><td>Pause between retries</td></tr><tr><td><code>linger.ms</code></td><td>5 (Kafka 4.x) or 0</td><td>How long to wait to fill a batch</td></tr><tr><td><code>max.block.ms</code></td><td>60000</td><td>How long <code>send</code> itself may block when the buffer is full or metadata is missing</td></tr></tbody></table>\n<p>The relationship is a rule: <code>delivery.timeout.ms</code> must be at least <code>linger.ms + request.timeout.ms</code>, or the producer rejects the configuration at startup. A message that cannot be delivered within <code>delivery.timeout.ms</code> fails with a <code>TimeoutException</code>, delivered to your callback, and that is the point at which your code decides: log and alert, retry from the beginning or write it to a fallback store.</p>\n<h2>Idempotence: retries without duplicates</h2>\n<p>Retries create a problem. If the broker appended a record and the acknowledgement was lost in the network, the producer retries, and the broker appends a second copy. Before idempotence, at least once delivery meant duplicates under failure. Setting <code>enable.idempotence=true</code> fixes it at the producer: the broker assigns the producer an ID, the producer numbers records per partition with a sequence and the broker discards a record whose sequence it has already seen. Retries become safe.</p>\n<p>Idempotence is on by default since Kafka 3.0, and it constrains other settings: <code>acks</code> must be <code>all</code>, <code>retries</code> greater than zero and <code>max.in.flight.requests.per.connection</code> at most 5. Within those limits ordering per partition is preserved even across retries, because the sequence numbers let the broker reject out of order batches. Without idempotence, more than one in-flight request plus retries can reorder records: a failed batch is retried after a later batch succeeds. If your design relies on per key ordering, idempotence is not optional.</p>\n<h2>A plain Java producer, configured for durability</h2>\n<p>Put the pieces together in the Kafka client without a framework. Everything is explicit, which makes it a good reference:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/kafka/DurableProducer.java\"><code class=\"language-java\">package dev.javahacks.kafka;\n\nimport org.apache.kafka.clients.producer.*;\nimport org.apache.kafka.common.errors.*;\nimport org.apache.kafka.common.serialization.StringSerializer;\n\nimport java.util.Properties;\nimport java.util.concurrent.TimeUnit;\n\npublic class DurableProducer implements AutoCloseable {\n\n    private final KafkaProducer&lt;String, String&gt; producer;\n\n    public DurableProducer(String bootstrapServers) {\n        Properties props = new Properties();\n        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);\n        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());\n        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());\n\n        props.put(ProducerConfig.ACKS_CONFIG, \"all\");\n        props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, \"true\");\n        props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, \"5\");\n        props.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, \"60000\");\n        props.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, \"15000\");\n        props.put(ProducerConfig.LINGER_MS_CONFIG, \"10\");\n        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, \"lz4\");\n        props.put(ProducerConfig.CLIENT_ID_CONFIG, \"orders-service\");\n\n        this.producer = new KafkaProducer&lt;&gt;(props);\n    }\n\n    public void sendAsync(String topic, String key, String value, FailureHandler onFailure) {\n        producer.send(new ProducerRecord&lt;&gt;(topic, key, value), (metadata, exception) -&gt; {\n            if (exception != null) {\n                onFailure.handle(topic, key, value, exception);      // the one place a loss becomes visible\n            }\n        });\n    }\n\n    public RecordMetadata sendAndWait(String topic, String key, String value) throws Exception {\n        return producer.send(new ProducerRecord&lt;&gt;(topic, key, value)).get(30, TimeUnit.SECONDS);\n    }\n\n    @Override\n    public void close() {\n        producer.flush();           // push out whatever is still buffered\n        producer.close();\n    }\n\n    @FunctionalInterface\n    public interface FailureHandler {\n        void handle(String topic, String key, String value, Exception cause);\n    }\n}</code></pre>\n<p>Read the choices. <code>acks</code>, <code>enable.idempotence</code> and <code>max.in.flight.requests.per.connection</code> state the contract; relying on defaults hides it. <code>delivery.timeout.ms</code> at 60 seconds bounds how long a message can sit retrying, which should match how long your caller can reasonably wait. The compression type <code>lz4</code> costs little CPU and reduces network and disk, and compression applies per batch, so it works better with a little <code>linger.ms</code>. <code>client.id</code> shows up in broker logs and metrics, which makes the producer identifiable when you debug. The <code>close</code> method flushes first: <code>close()</code> without <code>flush()</code> waits for in-flight batches up to a default timeout, but flushing explicitly makes the intent clear, and a service shutting down without it loses whatever was buffered.</p>\n<h2>send is asynchronous: check the result</h2>\n<p>The method <code>send</code> returns immediately after putting the record in an in-memory buffer. The actual write happens on a background thread, later. Whether it worked is known only through the returned <code>Future</code> or the callback. Code that calls <code>producer.send(record)</code> and moves on has told nobody about a failure:</p>\n<pre><code class=\"language-java\">producer.send(new ProducerRecord&lt;&gt;(\"order-events\", orderId, json));    // the result is thrown away</code></pre>\n<p>If the broker is down, the delivery timeout expires 60 seconds later and the failure lands in a future nobody is reading. The record is gone. Two disciplined patterns:</p>\n<p><strong>Fire with a callback</strong>, as <code>sendAsync</code> above, for throughput. The callback runs on the producer's I/O thread, so keep it short: log, count a metric, hand the failure to a fallback. Never block or call <code>send</code> from inside the callback.</p>\n<p><strong>Wait for the future</strong>, as <code>sendAndWait</code>, when the caller needs to know before proceeding, for instance before acknowledging an HTTP request. It limits throughput to one round trip per call from that thread, so use several threads, or collect futures and wait for them together.</p>\n<p>Errors are of two kinds, and the callback receives them as the <code>exception</code>:</p>\n<table><thead><tr><th>Exception</th><th>Meaning</th><th>Action</th></tr></thead><tbody><tr><td><code>TimeoutException</code></td><td>Delivery timeout reached</td><td>Alert; resend from a fallback store</td></tr><tr><td><code>NotEnoughReplicasException</code>, <code>NotEnoughReplicasAfterAppendException</code></td><td>ISR smaller than <code>min.insync.replicas</code></td><td>Retriable by the producer; if it persists, the cluster is degraded</td></tr><tr><td><code>RecordTooLargeException</code></td><td>Record exceeds <code>max.request.size</code> or the broker's limit</td><td>Not retriable; fix the message size, see below</td></tr><tr><td><code>SerializationException</code></td><td>The serializer failed</td><td>Not retriable; a bug in your data</td></tr><tr><td><code>AuthorizationException</code>, <code>InvalidTopicException</code></td><td>Configuration or ACL problem</td><td>Not retriable; fix the setup</td></tr><tr><td><code>ProducerFencedException</code></td><td>A newer producer with the same <code>transactional.id</code> took over</td><td>Close this producer</td></tr></tbody></table>\n<p>Retriable errors are retried by the client until the delivery timeout; you see them only when time runs out. Non retriable ones come back immediately, and each needs a different human response, which is why a generic \"log and ignore\" handler is the beginning of a lost-message story.</p>\n<p>A failure handler worth having writes the failed record to somewhere durable you control, such as a table, a local spill file or a dead letter topic on a different path, and raises an alert:</p>\n<pre><code class=\"language-java\">FailureHandler spill = (topic, key, value, cause) -&gt; {\n    log.error(\"kafka send failed topic={} key={} cause={}\", topic, key, cause.toString());\n    failedMessages.save(new FailedMessage(topic, key, value, cause.getClass().getSimpleName(), Instant.now()));\n    meterRegistry.counter(\"kafka.producer.failed\", \"topic\", topic).increment();\n};</code></pre>\n<p>A scheduled job can retry from the table. That turns an invisible loss into a visible queue.</p>\n<h2>Batching and throughput: what durability costs</h2>\n<p>Durability settings have a cost, and the right knobs claw back throughput without weakening the guarantee. Kafka producers batch records per partition:</p>\n<table><thead><tr><th>Setting</th><th>Effect</th><th>Tuning</th></tr></thead><tbody><tr><td><code>linger.ms</code></td><td>Wait this long for more records before sending a batch</td><td>5 to 20 ms for throughput; 0 for minimum latency</td></tr><tr><td><code>batch.size</code></td><td>Maximum bytes in a batch</td><td>32 to 128 KB when records are small and traffic is heavy</td></tr><tr><td><code>compression.type</code></td><td>Compress batches</td><td><code>lz4</code> or <code>zstd</code>; <code>zstd</code> compresses better for text and JSON</td></tr><tr><td><code>buffer.memory</code></td><td>Total memory for unsent records</td><td>Raise if <code>send</code> blocks (<code>max.block.ms</code>) under bursts</td></tr><tr><td><code>max.in.flight.requests.per.connection</code></td><td>Concurrent unacknowledged requests</td><td>Keep at 5 or fewer with idempotence</td></tr></tbody></table>\n<p>A small <code>linger.ms</code> is nearly free in latency terms and can multiply throughput, because more records share each request and each compressed batch. None of these affect the durability guarantee, which is why they are the right place to tune. What does weaken it, and should not be used to buy speed, is <code>acks</code> below <code>all</code>, <code>min.insync.replicas</code> of 1, or ignoring results.</p>\n<h2>The same thing in Spring Boot</h2>\n<p>Spring Boot with Spring for Apache Kafka sets up the producer from properties:</p>\n<pre data-filename=\"src/main/resources/application.yaml\"><code class=\"language-yaml\">spring:\n  kafka:\n    bootstrap-servers: ${KAFKA_BOOTSTRAP:localhost:9092}\n    producer:\n      acks: all\n      compression-type: lz4\n      key-serializer: org.apache.kafka.common.serialization.StringSerializer\n      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer\n      properties:\n        enable.idempotence: true\n        max.in.flight.requests.per.connection: 5\n        delivery.timeout.ms: 60000\n        request.timeout.ms: 15000\n        linger.ms: 10\n        client.id: orders-service</code></pre>\n<p>And the code that sends has to honour the asynchronous contract. <code>KafkaTemplate.send</code> returns a <code>CompletableFuture&lt;SendResult&gt;</code>:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/kafka/OrderEventPublisher.java\"><code class=\"language-java\">@Component\npublic class OrderEventPublisher {\n    private static final Logger log = LoggerFactory.getLogger(OrderEventPublisher.class);\n\n    private final KafkaTemplate&lt;String, OrderEvent&gt; kafka;\n    private final FailedMessageStore failed;\n    private final MeterRegistry metrics;\n\n    public OrderEventPublisher(KafkaTemplate&lt;String, OrderEvent&gt; kafka, FailedMessageStore failed, MeterRegistry metrics) {\n        this.kafka = kafka;\n        this.failed = failed;\n        this.metrics = metrics;\n    }\n\n    public void publish(OrderEvent event) {\n        kafka.send(\"order-events\", event.orderId(), event).whenComplete((result, error) -&gt; {\n            if (error != null) {\n                log.error(\"could not publish order event {}\", event.orderId(), error);\n                failed.save(\"order-events\", event.orderId(), event, error);\n                metrics.counter(\"orders.events.failed\").increment();\n            } else {\n                log.debug(\"published {} to partition {} offset {}\",\n                        event.orderId(), result.getRecordMetadata().partition(), result.getRecordMetadata().offset());\n            }\n        });\n    }\n\n    public SendResult&lt;String, OrderEvent&gt; publishAndWait(OrderEvent event) throws Exception {\n        return kafka.send(\"order-events\", event.orderId(), event).get(30, TimeUnit.SECONDS);\n    }\n}</code></pre>\n<p><code>whenComplete</code> is the callback, and the handler stores the failed message, logs with the exception and increments a metric. Do not call <code>kafka.send(...)</code> and discard the future. A Spring Boot application can also set a <code>ProducerListener</code> bean that logs every failure globally, as a safety net for places that forgot:</p>\n<pre><code class=\"language-java\">@Bean\nProducerListener&lt;String, OrderEvent&gt; producerListener() {\n    return new ProducerListener&lt;&gt;() {\n        @Override\n        public void onError(ProducerRecord&lt;String, OrderEvent&gt; record, RecordMetadata metadata, Exception exception) {\n            log.error(\"producer error for topic {} key {}\", record.topic(), record.key(), exception);\n        }\n    };\n}</code></pre>\n<h2>Large messages</h2>\n<p>A record larger than the limit fails immediately and permanently. The error message is the search query:</p>\n<pre><code class=\"language-text\">org.apache.kafka.common.errors.RecordTooLargeException: The message is 1048611 bytes when serialized which is larger than 1048576, which is the value of the max.request.size configuration.</code></pre>\n<p>Three limits must agree: the producer's <code>max.request.size</code> (default 1 MB), the broker's <code>message.max.bytes</code> and the topic's <code>max.message.bytes</code>, plus the consumer's <code>fetch.max.bytes</code>. Raising them all works, and large records hurt: they raise memory use on every client and slow replication. A better design stores big payloads (documents, images) in object storage and sends a reference in the event, the claim check pattern. A message that is a path and some metadata is a few hundred bytes.</p>\n<h2>Transactions: atomic writes across topics</h2>\n<p>Idempotence protects a single partition session. A <strong>transaction</strong> makes writes to several partitions, and the consumer offsets of a consume-process-produce loop, atomic: all become visible together or none do. Enable it by giving the producer a stable <code>transactional.id</code>:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/kafka/TransactionalProducer.java\"><code class=\"language-java\">public void publishBoth(String orderId, String paid, String shipment) {\n    producer.initTransactions();                     // once per producer, fences any older instance\n    try {\n        producer.beginTransaction();\n        producer.send(new ProducerRecord&lt;&gt;(\"payments\", orderId, paid));\n        producer.send(new ProducerRecord&lt;&gt;(\"shipments\", orderId, shipment));\n        producer.commitTransaction();\n    } catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {\n        producer.close();                            // fatal: another instance owns this transactional.id\n        throw e;\n    } catch (KafkaException e) {\n        producer.abortTransaction();                 // recoverable: roll back and retry the unit of work\n        throw e;\n    }\n}</code></pre>\n<p>Consumers see only committed transactions when they set <code>isolation.level=read_committed</code>; with the default <code>read_uncommitted</code> they also see records from aborted transactions. In Spring, set <code>spring.kafka.producer.transaction-id-prefix=orders-tx-</code> and the template becomes transactional, with <code>KafkaTransactionManager</code> used by <code>@Transactional</code>. The exactly-once semantics of the consume-transform-produce loop, and why they hold only inside Kafka, are the subject of <a href=\"/library/kafka-exactly-once-java-processing-transactions\">Kafka exactly-once processing with transactions</a>, and the general limits of the idea are in <a href=\"/library/exactly-once-delivery-two-generals-hard\">exactly-once delivery and the two generals</a>.</p>\n<p>Transactions have costs: commit markers, higher latency, a fenced-producer failure mode and the requirement that each producer instance use a unique, stable <code>transactional.id</code>. Use them where atomicity across topics or the read-process-write loop is the requirement, not as a default.</p>\n<h2>The dual write problem and the outbox</h2>\n<p>The most common durability failure has nothing to do with Kafka's settings. A service saves an order to its database and publishes an event:</p>\n<pre><code class=\"language-java\">@Transactional\npublic void placeOrder(Order order) {\n    orders.save(order);                  // commit happens when the method returns\n    kafka.send(\"order-events\", ...);     // happens before the commit, not atomically with it\n}</code></pre>\n<p>Two systems, two writes, no shared transaction. If the send succeeds and the commit then fails, the event announces an order that does not exist. If the commit succeeds and the process dies before the send, the order exists and no event ever goes out. Reordering the lines only swaps one failure for the other. Retrying cannot close the gap, since the crash that loses the send also loses the memory of needing to send it.</p>\n<p>The reliable fix is the <strong>transactional outbox</strong>. Write the event into an <code>outbox</code> table in the same database transaction as the business change, so both commit or neither does, and have a separate relay publish rows from the table to Kafka:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/outbox/OrderService.java\"><code class=\"language-java\">@Service\npublic class OrderService {\n    private final OrderRepository orders;\n    private final OutboxRepository outbox;\n    private final ObjectMapper json;\n\n    // constructor omitted\n\n    @Transactional\n    public void placeOrder(Order order) throws JsonProcessingException {\n        orders.save(order);\n        outbox.save(new OutboxEvent(UUID.randomUUID(), \"order-events\", order.getId().toString(),\n                json.writeValueAsString(OrderEvent.placed(order)), Instant.now()));\n    }\n}</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/outbox/OutboxRelay.java\"><code class=\"language-java\">@Component\npublic class OutboxRelay {\n    private final OutboxRepository outbox;\n    private final KafkaTemplate&lt;String, String&gt; kafka;\n\n    // constructor omitted\n\n    @Scheduled(fixedDelay = 500)\n    public void publishPending() {\n        for (OutboxEvent event : outbox.findTop100ByPublishedAtIsNullOrderByCreatedAt()) {\n            try {\n                kafka.send(event.topic(), event.key(), event.payload()).get(10, TimeUnit.SECONDS);\n                outbox.markPublished(event.id(), Instant.now());\n            } catch (Exception e) {\n                log.warn(\"outbox publish failed for {}, will retry\", event.id(), e);\n                return;                                  // keep order: stop at the first failure\n            }\n        }\n    }\n}</code></pre>\n<p>The relay gives <strong>at least once</strong> delivery: a crash between the send and <code>markPublished</code> publishes the event again on restart. That is acceptable when consumers are idempotent, using the event id, see <a href=\"/library/duplicate-messages-idempotent-consumer-handle-out\">handling duplicate messages with an idempotent consumer</a>. Running more than one relay needs a locking scheme so rows are not published concurrently (a <code>SELECT ... FOR UPDATE SKIP LOCKED</code>, covered in <a href=\"/library/jpa-pessimistic-locking-use\">pessimistic locking in JPA</a>). For high volume, replace the polling relay with change data capture reading the database log, described in <a href=\"/library/debezium-outbox-use-cdc\">the outbox pattern with Debezium</a>. Either way the database becomes the durable record of intent, and Kafka a reliable delivery channel from it.</p>\n<h2>Test durability</h2>\n<p>You can test the producer's configuration and behaviour with a real broker in a container. These tests are quick to write with Testcontainers and catch the mistakes that matter: a misconfigured producer, a topic created with the wrong settings and a callback that is never invoked.</p>\n<pre data-filename=\"src/test/java/dev/javahacks/kafka/DurableProducerIT.java\"><code class=\"language-java\">@Testcontainers\nclass DurableProducerIT {\n\n    @Container\n    static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse(\"apache/kafka:3.9.0\"));\n\n    @Test\n    void acknowledgedRecordsAreReadableAndOrderedPerKey() throws Exception {\n        try (var producer = new DurableProducer(kafka.getBootstrapServers())) {\n            for (int i = 0; i &lt; 100; i++) {\n                producer.sendAndWait(\"order-events\", \"order-42\", \"event-\" + i);\n            }\n        }\n\n        List&lt;String&gt; values = readAll(\"order-events\", kafka.getBootstrapServers());\n\n        assertThat(values).hasSize(100);\n        assertThat(values).isSortedAccordingTo(Comparator.comparingInt(v -&gt; Integer.parseInt(v.substring(6))));\n    }\n\n    @Test\n    void anUnreachableBrokerSurfacesAsAFailureNotASilentLoss() {\n        var failures = new CopyOnWriteArrayList&lt;Exception&gt;();\n        try (var producer = new DurableProducer(\"localhost:1\")) {            // nothing listens here\n            producer.sendAsync(\"order-events\", \"k\", \"v\", (t, k, v, e) -&gt; failures.add(e));\n        }\n\n        await().atMost(Duration.ofSeconds(90)).until(() -&gt; !failures.isEmpty());\n        assertThat(failures.get(0)).isInstanceOf(TimeoutException.class);\n    }\n}</code></pre>\n<p>The second test is the valuable one: it proves that a dead broker produces a callback with an exception, within the delivery timeout, and so your failure handler actually gets called. For a smaller timeout in tests, make <code>delivery.timeout.ms</code> a constructor parameter. To test the <code>min.insync.replicas</code> behaviour you need a multi broker cluster, which Testcontainers can start with a Kafka cluster module or a Compose file, then stop two brokers and assert that sends fail with <code>NotEnoughReplicasException</code> and recover when a broker returns. That is more setup, and worth doing once, as a staging test. <a href=\"/library/test-kafka-testcontainers-consumers\">Testing Kafka consumers with Testcontainers</a> covers the consuming side.</p>\n<h2>Reading offsets and metadata back</h2>\n<p>A producer that wants proof of durability can ask for it. The <code>RecordMetadata</code> returned by a successful send names the partition and offset the record was written at, and with <code>acks=all</code> that offset is committed. Logging them at debug level, as the Spring publisher does, gives support engineers a way to answer \"was this event written\": search the log for the order id and read the partition and offset, then confirm with the console consumer that the record is at that position.</p>\n<pre><code class=\"language-bash\">kafka-console-consumer.sh --bootstrap-server broker:9092 --topic order-events \\\n  --partition 3 --offset 118402 --max-messages 1 --property print.key=true --property print.timestamp=true</code></pre>\n<pre><code class=\"language-text\">CreateTime:1793672042331\torder-42\t{\"type\":\"ORDER_PLACED\",\"orderId\":\"order-42\"}</code></pre>\n<p>The timestamp, key and value come back, which closes the loop between the application's belief and the broker's log. When a downstream team says the event never arrived, this check settles in one minute whether the problem is on the producing side or the consuming side, and it replaces a meeting. Make it part of the runbook for the service, with the exact commands and the broker addresses for each environment.</p>\n<h2>Monitor the things that precede loss</h2>\n<p>Durability fails slowly and then suddenly. Watch producer and broker signals:</p>\n<table><thead><tr><th>Metric</th><th>Where</th><th>What it tells you</th></tr></thead><tbody><tr><td><code>record-error-rate</code>, <code>record-error-total</code></td><td>Producer</td><td>Records that failed after retries</td></tr><tr><td><code>record-retry-rate</code></td><td>Producer</td><td>Trouble reaching a leader; rising means instability</td></tr><tr><td><code>request-latency-avg</code>, <code>request-latency-max</code></td><td>Producer</td><td>Slow brokers or network</td></tr><tr><td><code>buffer-available-bytes</code>, <code>bufferpool-wait-ratio</code></td><td>Producer</td><td>Buffer pressure; <code>send</code> about to block</td></tr><tr><td><code>UnderReplicatedPartitions</code></td><td>Broker</td><td>Followers behind; one failure from trouble</td></tr><tr><td><code>IsrShrinksPerSec</code>, <code>IsrExpandsPerSec</code></td><td>Broker</td><td>Replicas falling out of and back into sync</td></tr><tr><td><code>OfflinePartitionsCount</code></td><td>Controller</td><td>Partitions with no leader; writes failing</td></tr></tbody></table>\n<p>Micrometer exposes the client's metrics with one line:</p>\n<pre><code class=\"language-java\">@Bean\nMeterBinder kafkaProducerMetrics(ProducerFactory&lt;String, OrderEvent&gt; factory) {\n    return registry -&gt; new KafkaClientMetrics(factory.createProducer()).bindTo(registry);\n}</code></pre>\n<p>Spring Boot also binds the producer metrics to the registry automatically in recent versions when Actuator and Micrometer are present, tagged by <code>client.id</code>. Alert on <code>record-error-total</code> increasing, on retries sustained above a baseline and on any under-replicated partitions for more than a few minutes. Consumer lag is the other half; see <a href=\"/library/kafka-consumer-lag-monitor-java\">monitoring Kafka consumer lag from Java</a>.</p>\n<h2>Inside the producer: where a record waits</h2>\n<p>Knowing what happens between <code>send</code> and the network explains most of the settings. A <code>KafkaProducer</code> is a small pipeline. When you call <code>send</code>, the calling thread serialises the key and value, picks a partition (from the key's hash, or round robin when the key is null) and appends the record to a <strong>record accumulator</strong>, an in-memory structure holding one queue of batches per partition. The call returns at that point; the record has not left the process. A separate <strong>sender thread</strong> drains the accumulator: it collects ready batches, groups them by destination broker and sends one request per broker. A batch is ready when it is full (<code>batch.size</code>), when it has waited <code>linger.ms</code> or when the producer is flushing or closing.</p>\n<p>Three consequences follow. First, a record sits in memory for at least <code>linger.ms</code> and until a response arrives, so a crash during that window loses it, which is the gap the outbox closes. Second, if the sender cannot keep up, for instance because the broker is slow, the accumulator fills to <code>buffer.memory</code>, and <code>send</code> blocks for up to <code>max.block.ms</code> and then throws <code>TimeoutException: Failed to allocate memory within the configured max blocking time</code>. That is backpressure reaching your request thread, and it is a signal to read, not to silence by raising the buffer. Third, a batch that failed with a retriable error goes back to the head of its partition's queue, which is how ordering is preserved under idempotence.</p>\n<p>The partitioner matters for durability in one respect: it fixes which leader a record goes to. With a key, all records for that key go to one partition and keep their order; with no key, records are spread, and ordering across them is not defined. If an event stream for one order must stay ordered, key it by order id, as <a href=\"/library/kafka-partitions-keys-java-use-topics\">Kafka partitions and keys</a> explains.</p>\n<h2>Serialization is a failure point too</h2>\n<p>A serializer that throws on one bad object stops the record before it reaches the accumulator, as a <code>SerializationException</code> raised synchronously from <code>send</code>, unlike network errors which arrive in the callback. With Spring's <code>JsonSerializer</code>, a type that Jackson cannot write, a cyclic object graph or a missing module for <code>java.time</code>, fails here:</p>\n<pre><code class=\"language-text\">org.apache.kafka.common.errors.SerializationException: Can't convert value of class dev.javahacks.OrderEvent to class org.apache.kafka.common.serialization.StringSerializer specified in value.serializer</code></pre>\n<p>This particular message means the serializer configured does not match the type sent, a configuration mistake that tests catch immediately. Handle synchronous exceptions around <code>send</code> as well as the asynchronous ones, or an unexpected payload takes down the thread that was publishing. For events that will be consumed by other teams, a schema registry with Avro or Protobuf adds a compatibility check at produce time, so an incompatible change fails in the producer instead of poisoning consumers. The approach is described in <a href=\"/library/avro-schema-registry-java-version-event\">versioning events with Avro and a schema registry</a>. Durability is also about being able to read the data later, and a record that no consumer can deserialise is lost in every way that matters.</p>\n<h2>Operating durable producers through broker restarts</h2>\n<p>The settings pay off during routine operations. Rolling a Kafka cluster, upgrading brokers or patching hosts, is done one broker at a time. With replication factor 3 and <code>min.insync.replicas=2</code>, taking one broker down leaves two replicas, writes continue and producers see brief, retriable errors for the partitions whose leader moved: <code>NOT_LEADER_OR_FOLLOWER</code>, handled inside the client by refreshing metadata and retrying, which idempotence makes safe. The operator's job is to wait between restarts until the restarted broker has rejoined every ISR, which means no under-replicated partitions, before touching the next one. If that wait is skipped, two replicas of a partition are briefly absent, the ISR drops below the minimum and producers receive <code>NotEnoughReplicasException</code>; with <code>acks=all</code> and a sensible delivery timeout the writes are retried until the broker returns and nothing is lost, but a timeout that is too short turns the rolling restart into failed sends.</p>\n<p>This is the strongest argument for stating the delivery timeout deliberately. A restart of a broker typically takes tens of seconds to a few minutes for the ISR to recover. A <code>delivery.timeout.ms</code> of 30 seconds fails sends during a normal maintenance window, while 120 seconds rides through it. Set it from the worst maintenance event you accept, and compare it with how long the caller can wait. If the caller cannot wait that long, the answer is the outbox, so the request returns after the database commit and the relay absorbs the broker's slow minutes.</p>\n<h2>Disk, retention and what \"durable\" means over time</h2>\n<p>Durability in Kafka is bounded by retention. A record is kept for <code>retention.ms</code> (seven days by default) or until a partition exceeds <code>retention.bytes</code>, then it is deleted whether or not any consumer has read it. A consumer that is down for longer than the retention loses the records it did not read, and no producer setting prevents that. Size the retention to the longest outage you intend to survive, plus the time to catch up, and monitor consumer lag against it. Topics that hold the source of truth, for example a changelog that rebuilds state, use log compaction (<code>cleanup.policy=compact</code>), which keeps the latest record per key indefinitely instead of deleting by age. Disk is the other bound: a full broker disk stops writes, so alert on usage well before it fills, and remember replication multiplies the storage, three copies of everything.</p>\n<h2>Notes for Kafka 4</h2>\n<p>Kafka 4.0 removed ZooKeeper, so clusters run in KRaft mode, and raised the minimum supported client and broker Java versions. For producers the visible changes are small: the default <code>linger.ms</code> became 5, so batches form even with the default configuration, and the idempotent, <code>acks=all</code> configuration is the baseline. Clients from the 3.x line still work with a 4.x cluster for the supported compatibility range, and the durable settings in this guide are unchanged. Read the upgrade notes for your exact versions before changing a production cluster, and test the producer against the new broker version with the Testcontainers image set to match.</p>\n<h2>A worked incident: reading the producer log</h2>\n<p>A concrete case shows how the settings and the code combine when something goes wrong. A deployment restarts one of three brokers while the orders service is publishing. The service logs, in order:</p>\n<pre><code class=\"language-text\">WARN  [Producer clientId=orders-service] Got error produce response with correlation id 8814 on topic-partition order-events-3, retrying (2147483646 attempts left). Error: NOT_LEADER_OR_FOLLOWER\nINFO  [Producer clientId=orders-service] Resetting the last seen epoch of partition order-events-3 to 41 since the associated topicId changed\nWARN  [Producer clientId=orders-service] Got error produce response with correlation id 8920 on topic-partition order-events-7, retrying (2147483645 attempts left). Error: NOT_ENOUGH_REPLICAS\nINFO  orders.events.published partition=3 offset=118402</code></pre>\n<p>Read it line by line. <code>NOT_LEADER_OR_FOLLOWER</code> on partition 3 is the leader moving off the restarting broker: the client refreshed its metadata and retried, and nothing needs doing. The \"attempts left\" number is huge because retries are bounded by time, not count. <code>NOT_ENOUGH_REPLICAS</code> on partition 7 is the more serious sign: for a moment that partition had fewer in-sync replicas than <code>min.insync.replicas</code>, which happens when a second replica is slow or restarting while the first is down. The producer kept retrying, the replicas caught up and the final line shows a successful publish with an offset. No callback fired with an error, no message was lost, and the only cost was latency on those two partitions for a short time.</p>\n<p>Now change one thing: set <code>delivery.timeout.ms</code> to 5000 and repeat the restart. The same warnings appear, but after five seconds the callback receives <code>TimeoutException: Expiring 14 record(s) for order-events-7: 5003 ms has passed since batch creation</code>. Fourteen records are now the application's problem, and the failure handler decides what happens to them. That contrast is the point of this guide in one example: the infrastructure behaves identically, and what changes between \"the restart was invisible\" and \"we lost fourteen orders\" is the timeout and the handler.</p>\n<h2>Failure scenarios, and what each setting does</h2>\n<table><thead><tr><th>Scenario</th><th>With the durable settings</th><th>With weak settings</th></tr></thead><tbody><tr><td>A follower broker restarts</td><td>ISR shrinks to 2, writes continue, follower catches up</td><td>Same</td></tr><tr><td>The leader crashes mid-write</td><td>The producer's request fails or times out, retries to the new leader, idempotence prevents a duplicate</td><td><code>acks=1</code>: an acknowledged record may be lost</td></tr><tr><td>Two of three brokers are down</td><td>Writes fail with <code>NotEnoughReplicasException</code>; no data lost, availability reduced</td><td><code>min.insync.replicas=1</code>: writes continue on one replica and are lost if it dies</td></tr><tr><td>A network partition isolates the producer</td><td><code>TimeoutException</code> after the delivery timeout, callback fires</td><td><code>acks=0</code>: no signal at all</td></tr><tr><td>The application crashes with records in the buffer</td><td>Buffered records are lost; records acknowledged before the crash are safe</td><td>Same, which is why the outbox exists</td></tr><tr><td>The application is shut down cleanly</td><td><code>flush</code> and <code>close</code> send what remains</td><td><code>close</code> without flush can drop the tail</td></tr><tr><td>The broker disk fills</td><td>The broker stops accepting writes; producers time out</td><td>Same, monitor disk</td></tr><tr><td>A duplicate is sent because the ack was lost</td><td>Idempotence discards it</td><td>Without idempotence: two copies in the topic</td></tr></tbody></table>\n<p>The one scenario the producer settings cannot protect against is a crash with unsent records in memory, which is the reason the outbox pattern exists and the reason to prefer it when a message must follow a database change.</p>\n<h2>Three configuration profiles</h2>\n<p>Different workloads sit at different points:</p>\n<table><thead><tr><th>Setting</th><th>Maximum durability</th><th>Balanced (the default recommendation)</th><th>Throughput first, loss tolerable</th></tr></thead><tbody><tr><td><code>acks</code></td><td>all</td><td>all</td><td>1</td></tr><tr><td><code>enable.idempotence</code></td><td>true</td><td>true</td><td>false</td></tr><tr><td>Topic replication / <code>min.insync.replicas</code></td><td>3 / 2</td><td>3 / 2</td><td>3 / 1</td></tr><tr><td><code>delivery.timeout.ms</code></td><td>120000</td><td>60000</td><td>30000</td></tr><tr><td><code>linger.ms</code></td><td>0 to 5</td><td>10</td><td>50</td></tr><tr><td><code>compression.type</code></td><td>lz4</td><td>lz4</td><td>zstd</td></tr><tr><td>Transactions</td><td>when atomicity needed</td><td>rarely</td><td>no</td></tr><tr><td>Result handling</td><td>Wait or callback with spill</td><td>Callback with spill</td><td>Callback and metric</td></tr></tbody></table>\n<p>Use the first or second profile for business events: orders, payments, state changes. The third suits telemetry, clickstream and logs where occasional loss is acceptable, and even there <code>acks=all</code> is rarely the bottleneck.</p>\n<h2>Common mistakes</h2>\n<p><strong>Ignoring the future.</strong> The commonest, covered above.</p>\n<p><strong>Relying on defaults across versions.</strong> The defaults changed in Kafka 3.0; code that worked unchanged for years may be running with settings its authors never saw. State the durability settings in your configuration.</p>\n<p><strong>Topic settings forgotten.</strong> <code>acks=all</code> with <code>min.insync.replicas=1</code> on a topic created by auto creation is not durable. Disable auto topic creation in production (<code>auto.create.topics.enable=false</code>) and create topics explicitly.</p>\n<p><strong>Message keys that skew.</strong> A key with one dominant value sends most traffic to one partition, which is a throughput and availability issue more than durability, treated in <a href=\"/library/kafka-partitions-keys-java-use-topics\">Kafka partitions and keys</a>.</p>\n<p><strong>Blocking inside the callback.</strong> The callback runs on the producer's network thread; blocking it stalls all sends.</p>\n<p><strong>Creating a producer per message.</strong> A <code>KafkaProducer</code> is thread safe and expensive to build. Create one per application, or one per <code>transactional.id</code> when using transactions, and share it.</p>\n<p><strong>Unbounded retries without a timeout.</strong> Older configurations set <code>retries=Integer.MAX_VALUE</code> with <code>max.block.ms</code> unlimited, and a broker outage made request threads hang forever. Use the delivery timeout and a bounded wait.</p>\n<p><strong>Treating success as end to end.</strong> A durable producer gets the record safely into Kafka. Whether a consumer processes it exactly once is a separate design problem, see <a href=\"/library/reliable-kafka-consumer-java-write\">writing a reliable Kafka consumer</a> and <a href=\"/library/dead-letter-queue-kafka-spring-use\">handling dead letters</a>.</p>\n<h2>A review checklist</h2>\n<ol><li>Topic: replication factor 3, <code>min.insync.replicas=2</code>, unclean election off, created explicitly.</li><li>Producer: <code>acks=all</code>, <code>enable.idempotence=true</code>, in-flight at most 5, delivery timeout stated.</li><li>Code: every send has a callback or a waited future; failures are logged, counted and stored.</li><li>Shutdown: <code>flush</code> then <code>close</code>, and the application waits for in-flight work first.</li><li>Consistency: a database change that must produce an event uses an outbox or a transaction, not two independent writes.</li><li>Consumers: <code>isolation.level=read_committed</code> if transactions are used; idempotent processing.</li><li>Tests: a broker-down test proving the callback fires; a staging test with a broker killed.</li><li>Monitoring: producer error and retry rates, under-replicated partitions, alerts wired and tried.</li></ol>\n<h2>A last check before production</h2>\n<p>Before a producer goes live, send a message with the broker's leader killed and watch the result. The send should either succeed after a short retry or fail with an exception your handler catches, with no third outcome. Run the same experiment with the broker count reduced below <code>min.insync.replicas</code> and confirm the failure is loud. A durability setting that has never been seen to fail safely is a belief, not a property, and this ten minute test replaces the belief with evidence.</p>\n<h2>When this does not apply</h2>\n<p>If a message can be lost without anyone caring, such as a debug trace or a sampled metric, the cheaper settings are the right ones, and over-engineering durability wastes latency and money. If you cannot control the topic, because another team owns the cluster and its defaults, the producer settings still help but the guarantee is the weaker of the two sides; ask for the topic settings in writing. Kafka is not the only way to move events reliably between services: a database queue or a broker with built in acknowledgements, as in <a href=\"/library/rabbitmq-acks-dead-letter-use-retries\">using RabbitMQ acks, retries and dead letters</a>, is simpler if you do not need Kafka's log semantics. For the primary sources, read the <a href=\"https://kafka.apache.org/documentation/#producerconfigs\">Apache Kafka documentation on the producer configs</a>, the <a href=\"https://kafka.apache.org/documentation/#replication\">section on design and replication</a> and the <a href=\"https://docs.spring.io/spring-kafka/reference/\">Spring for Apache Kafka reference</a>.</p>","date_published":"2026-11-14T04:15:31+00:00","tags":["Microservices"]},{"id":"https://javahacks.dev/library/playwright-java-write-end-end-tests","url":"https://javahacks.dev/library/playwright-java-write-end-end-tests","title":"Playwright for Java End to End Testing Guide for Web Apps","summary":"A complete guide to Playwright for Java: locators, auto waiting, JUnit fixtures, Spring Boot setup, page objects, auth, tracing, CI and flakiness.","content_html":"<p>End to end tests have a deserved reputation: slow, brittle and trusted by nobody. The tests that drive a browser are where regressions in real user journeys get caught, such as the checkout that no unit test can see is broken because a button is covered by a banner, and they are where teams give up after the hundredth intermittent failure. Most of that brittleness comes from tools that make you manage timing yourself, with explicit waits, sleeps and retries scattered through the code. <strong>Playwright</strong> was designed to remove that class of problem. It controls Chromium, Firefox and WebKit through one API, waits automatically for elements to be ready before acting and retries assertions until they hold. It has an official Java binding, so tests live in your Maven or Gradle build beside the application and run with JUnit. This guide takes you from the first test to a maintainable suite: setup, locators, actions and assertions, JUnit lifecycle, Spring Boot integration with a real database, page objects, authentication, network control, debugging with traces, parallel execution and continuous integration. Every section has code, and the final sections cover what makes suites flaky and when a browser test is the wrong tool.</p>\n<p>The line to remember: <strong>a good end to end test describes what a user does in the words a user would use, and lets the tool worry about timing.</strong> The sections below are how to follow it in Java. For the tests that should be the bulk of your suite, see <a href=\"/library/test-pyramid-java-services-where-breaks\">the test pyramid for Java services</a> and <a href=\"/library/unit-vs-integration-tests-java-end\">unit versus integration tests</a>.</p>\n<h2>Setup</h2>\n<p>Add the dependency to the test scope of the project:</p>\n<pre data-filename=\"pom.xml\"><code class=\"language-xml\">&lt;dependency&gt;\n    &lt;groupId&gt;com.microsoft.playwright&lt;/groupId&gt;\n    &lt;artifactId&gt;playwright&lt;/artifactId&gt;\n    &lt;version&gt;1.49.0&lt;/version&gt;\n    &lt;scope&gt;test&lt;/scope&gt;\n&lt;/dependency&gt;</code></pre>\n<p>Playwright needs browser binaries, which it downloads on first use into a cache directory. Install them explicitly in CI and on a new machine so a test run does not spend its first minute downloading:</p>\n<pre><code class=\"language-bash\">mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=\"install --with-deps chromium\"</code></pre>\n<p>The <code>--with-deps</code> flag also installs the operating system libraries the browser needs, which matters on a bare Linux container. Drop the browser name to install all three. The Java library, the driver it runs and the browsers are version locked, so upgrading the dependency means reinstalling the browsers.</p>\n<h2>The first test</h2>\n<p>The smallest useful test creates a Playwright instance, launches a browser, opens a page, acts and asserts:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/e2e/FirstPlaywrightTest.java\"><code class=\"language-java\">package dev.javahacks.e2e;\n\nimport com.microsoft.playwright.*;\nimport org.junit.jupiter.api.Test;\n\nimport static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;\n\nclass FirstPlaywrightTest {\n\n    @Test\n    void searchShowsMatchingResults() {\n        try (Playwright playwright = Playwright.create()) {\n            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));\n            BrowserContext context = browser.newContext();\n            Page page = context.newPage();\n\n            page.navigate(\"https://shop.example.test\");\n            page.getByPlaceholder(\"Search products\").fill(\"java book\");\n            page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Search\")).click();\n\n            assertThat(page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName(\"Results for java book\")))\n                    .isVisible();\n            assertThat(page.locator(\".product-card\")).hasCount(12);\n        }\n    }\n}</code></pre>\n<p>Four objects form a hierarchy. <code>Playwright</code> owns the driver process. A <code>Browser</code> is one browser instance. A **<code>BrowserContext</code>** is an isolated session inside it, like an incognito profile, with its own cookies and storage, cheap to create. A <code>Page</code> is one tab. The structure matters because it dictates test isolation: a fresh context per test costs milliseconds and guarantees that one test's login does not leak into the next, where launching a fresh browser per test costs seconds.</p>\n<p>Notice what the test does not contain: no sleep, no explicit wait, no <code>WebDriverWait</code>. Clicking waits for the button to exist, be visible, be stable (not animating) and receive events. <code>assertThat(...).hasCount(12)</code> retries for up to five seconds until the count is 12 and fails with a message showing the last observed value if it never is.</p>\n<h2>Locators: find what users see</h2>\n<p>A <strong>locator</strong> describes how to find an element and is evaluated fresh each time it is used, so it never goes stale like a Selenium <code>WebElement</code> can. Playwright's locator methods are ranked by how closely they match what a user perceives:</p>\n<table><thead><tr><th>Locator</th><th>Finds</th><th>Prefer for</th></tr></thead><tbody><tr><td><code>getByRole(role, name)</code></td><td>Elements by ARIA role and accessible name</td><td>Buttons, links, headings, form fields: the first choice</td></tr><tr><td><code>getByLabel(\"Email\")</code></td><td>Form controls by their label</td><td>Inputs</td></tr><tr><td><code>getByPlaceholder</code></td><td>By placeholder text</td><td>Inputs without labels</td></tr><tr><td><code>getByText(\"Welcome back\")</code></td><td>By visible text</td><td>Static text and messages</td></tr><tr><td><code>getByAltText</code>, <code>getByTitle</code></td><td>By alt text or title</td><td>Images, tooltips</td></tr><tr><td><code>getByTestId(\"checkout-total\")</code></td><td>By a <code>data-testid</code> attribute</td><td>When no user visible handle exists</td></tr><tr><td><code>locator(\"css or xpath\")</code></td><td>By CSS or XPath</td><td>Last resort</td></tr></tbody></table>\n<pre><code class=\"language-java\">page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Add to basket\")).click();\npage.getByLabel(\"Email\").fill(\"ana@example.test\");\npage.getByRole(AriaRole.ROW, new Page.GetByRoleOptions().setName(\"Java Book\"))\n        .getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Remove\")).click();</code></pre>\n<p>The third line shows <strong>chaining</strong>: find the table row for one product, then the button inside that row only. Scoping like this replaces brittle indexed selectors such as <code>button:nth-child(3)</code>. Role based locators have a second benefit: they pass only when the page is accessible, so a test that cannot find a button by its role is telling you the markup has an accessibility problem. If an element has no role, label or text a user can see, add a <code>data-testid</code> and configure Playwright to use it:</p>\n<pre><code class=\"language-java\">playwright.selectors().setTestIdAttribute(\"data-test\");</code></pre>\n<p>Avoid selectors tied to layout or styling (<code>div &gt; div:nth-child(2) .btn-primary</code>): they break whenever a designer moves something. Locators are strict by default: if one matches more than one element and you act on it, Playwright throws a <code>strict mode violation</code>, naming the matches, which is a feature, since an ambiguous locator would otherwise click an arbitrary element. Narrow it, or use <code>first()</code>, <code>last()</code> or <code>nth(n)</code> deliberately.</p>\n<h2>Actions and auto waiting</h2>\n<p>The actions you use most are <code>click</code>, <code>fill</code>, <code>check</code>, <code>selectOption</code>, <code>press</code>, <code>hover</code> and <code>setInputFiles</code>. Before each, Playwright runs <strong>actionability checks</strong>: the element must be attached to the DOM, visible, stable (not moving), enabled and receiving events at the click point, not covered by another element. It retries these until they pass or the action timeout (30 seconds by default) expires, then fails with a log of which check failed:</p>\n<pre><code class=\"language-text\">com.microsoft.playwright.TimeoutError: Error {\n  message='Timeout 30000ms exceeded.\nCall log:\n  - waiting for getByRole(AriaRole.BUTTON, name=\"Pay now\")\n  -   locator resolved to &lt;button disabled class=\"btn\"&gt;Pay now&lt;/button&gt;\n  -   attempting click action\n  -   waiting for element to be visible, enabled and stable\n  -     element is not enabled\n  -   retrying click action</code></pre>\n<p>That call log is the main debugging aid: it states that the button was found but disabled, which points at the form validation, not at the test. Compare it with a Selenium <code>NoSuchElementException</code>, which says almost nothing.</p>\n<p>Common actions:</p>\n<pre><code class=\"language-java\">page.getByLabel(\"Quantity\").fill(\"3\");\npage.getByLabel(\"I accept the terms\").check();\npage.getByLabel(\"Country\").selectOption(\"Vietnam\");\npage.keyboard().press(\"Enter\");\npage.getByLabel(\"Upload invoice\").setInputFiles(Paths.get(\"src/test/resources/invoice.pdf\"));\npage.getByText(\"Order details\").hover();</code></pre>\n<p><code>fill</code> clears the field and sets the value, firing the input events a framework needs; use <code>pressSequentially</code> when a widget reacts to individual keystrokes, such as an autocomplete. Do not sleep: <code>page.waitForTimeout(2000)</code> exists, and each use in a test is a sign that a proper wait condition is missing.</p>\n<h2>Web first assertions</h2>\n<p><code>PlaywrightAssertions.assertThat</code> takes a locator, a page or a response and offers assertions that <strong>retry</strong> until they pass:</p>\n<pre><code class=\"language-java\">assertThat(page).hasURL(Pattern.compile(\".*/orders/\\\\d+\"));\nassertThat(page).hasTitle(\"Order confirmation\");\nassertThat(page.getByText(\"Thank you for your order\")).isVisible();\nassertThat(page.locator(\".basket-count\")).hasText(\"3\");\nassertThat(page.getByLabel(\"Email\")).hasValue(\"ana@example.test\");\nassertThat(page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Pay now\"))).isEnabled();\nassertThat(page.locator(\".error\")).hasCount(0);\nassertThat(page.locator(\".toast\")).containsText(\"saved\");</code></pre>\n<p>Contrast this with JUnit's <code>assertEquals(3, Integer.parseInt(page.locator(\".basket-count\").textContent()))</code>, which reads the text once, immediately, and fails if the page has not finished updating: the classic flaky test. A web first assertion waits up to its timeout (5 seconds by default, <code>assertThat(...).setTimeout</code>-configurable) for the condition. Use them for anything the page changes. Use plain JUnit or AssertJ assertions for values that are static once read, such as a computed total from your own test data. Mixing the two is natural.</p>\n<p>Two assertion habits are worth adopting. Assert on user visible outcomes, not implementation: the confirmation message, the URL, the new row in the table. And assert negatives with the matching retrying form, <code>assertThat(locator).isHidden()</code> or <code>hasCount(0)</code>, not by checking that an element is absent once.</p>\n<h2>JUnit 5 structure</h2>\n<p>Launching a browser for every test is slow and wasteful. The standard arrangement is one <code>Playwright</code> and <code>Browser</code> per test class, a new <code>BrowserContext</code> and <code>Page</code> per test:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/e2e/PlaywrightTest.java\"><code class=\"language-java\">package dev.javahacks.e2e;\n\nimport com.microsoft.playwright.*;\nimport org.junit.jupiter.api.*;\n\npublic abstract class PlaywrightTest {\n    static Playwright playwright;\n    static Browser browser;\n\n    BrowserContext context;\n    Page page;\n\n    @BeforeAll\n    static void launchBrowser() {\n        playwright = Playwright.create();\n        browser = playwright.chromium().launch(new BrowserType.LaunchOptions()\n                .setHeadless(!Boolean.getBoolean(\"headed\")));\n    }\n\n    @AfterAll\n    static void closeBrowser() {\n        browser.close();\n        playwright.close();\n    }\n\n    @BeforeEach\n    void createContext() {\n        context = browser.newContext(new Browser.NewContextOptions()\n                .setViewportSize(1280, 800)\n                .setLocale(\"en-US\")\n                .setTimezoneId(\"Asia/Ho_Chi_Minh\"));\n        context.setDefaultTimeout(10_000);\n        page = context.newPage();\n    }\n\n    @AfterEach\n    void closeContext() {\n        context.close();\n    }\n}</code></pre>\n<p>Subclasses just use <code>page</code>. Run with <code>-Dheaded=true</code> to watch the browser while writing a test. Fix the locale, time zone and viewport in the context options so the tests do not depend on the machine they run on, since a date rendered in the developer's zone and in the CI server's zone is a classic source of \"passes locally\". Playwright objects are <strong>not thread safe</strong>: if tests run in parallel, each thread needs its own <code>Playwright</code> instance, so use a <code>ThreadLocal</code> holder or run test classes in separate JVM forks.</p>\n<h2>Testing your own Spring Boot application</h2>\n<p>For an application in the same repository, start it as part of the test, on a random port, with a real database in a container, and drive it through a browser:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/e2e/CheckoutE2ETest.java\"><code class=\"language-java\">@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\n@Testcontainers\nclass CheckoutE2ETest extends PlaywrightTest {\n\n    @Container\n    @ServiceConnection\n    static PostgreSQLContainer&lt;?&gt; db = new PostgreSQLContainer&lt;&gt;(\"postgres:17\");\n\n    @LocalServerPort\n    int port;\n\n    @Autowired\n    TestData data;                         // helper that inserts fixtures through repositories\n\n    @Test\n    void aCustomerCanBuyABookAsAGuest() {\n        Product book = data.product(\"Java Book\", \"29.00\");\n\n        page.navigate(\"http://localhost:\" + port + \"/\");\n        page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName(\"Java Book\")).click();\n        page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Add to basket\")).click();\n        page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName(\"Basket (1)\")).click();\n\n        assertThat(page.getByRole(AriaRole.ROW, new Page.GetByRoleOptions().setName(\"Java Book\"))).isVisible();\n        assertThat(page.getByTestId(\"basket-total\")).hasText(\"$29.00\");\n\n        page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Checkout\")).click();\n        page.getByLabel(\"Email\").fill(\"ana@example.test\");\n        page.getByLabel(\"Card number\").fill(\"4242424242424242\");\n        page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Pay now\")).click();\n\n        assertThat(page.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName(\"Thank you for your order\"))).isVisible();\n        assertThat(data.ordersFor(\"ana@example.test\")).hasSize(1);           // verify the side effect in the database\n    }\n}</code></pre>\n<p>Three points about this design. The database is real, through <a href=\"/library/testcontainers-service-connection-use-spring-boot\">Testcontainers' service connection</a>, so the test exercises the real persistence layer. Fixtures are created through application code or SQL (<code>TestData</code>) rather than by clicking through screens, because a test should drive the UI only for the behaviour under test, not for its preconditions. And the final assertion checks the database, since a UI that says \"thank you\" without saving an order is the bug that matters. External services, the card processor above, should be stubbed at the HTTP level, with WireMock as in <a href=\"/library/wiremock-java-test-mock-external-apis\">mocking external APIs with WireMock</a>, never called for real.</p>\n<h2>Page objects</h2>\n<p>A test that spells out every locator is hard to maintain: changing the label of one button means editing twenty tests. The <strong>page object</strong> pattern wraps a page's locators and actions in a class named for what the page offers:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/e2e/pages/BasketPage.java\"><code class=\"language-java\">public class BasketPage {\n    private final Page page;\n\n    public BasketPage(Page page) {\n        this.page = page;\n    }\n\n    public BasketPage open(String baseUrl) {\n        page.navigate(baseUrl + \"/basket\");\n        return this;\n    }\n\n    public BasketPage removeItem(String productName) {\n        page.getByRole(AriaRole.ROW, new Page.GetByRoleOptions().setName(productName))\n                .getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Remove\")).click();\n        return this;\n    }\n\n    public CheckoutPage checkout() {\n        page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Checkout\")).click();\n        return new CheckoutPage(page);\n    }\n\n    public void assertContains(String productName) {\n        assertThat(page.getByRole(AriaRole.ROW, new Page.GetByRoleOptions().setName(productName))).isVisible();\n    }\n\n    public void assertTotal(String expected) {\n        assertThat(page.getByTestId(\"basket-total\")).hasText(expected);\n    }\n}</code></pre>\n<p>The test now reads as the user journey:</p>\n<pre><code class=\"language-java\">new BasketPage(page).open(baseUrl).removeItem(\"Old Book\").checkout().payAs(\"ana@example.test\", \"4242424242424242\");</code></pre>\n<p>Keep assertions about the page's state in the page object (<code>assertTotal</code>), and the expectations of the scenario in the test. Methods that navigate return the next page object, so the compiler guides you through the flow. Do not over abstract: a page object per significant page or component is enough, and a helper that is used once is not worth the indirection.</p>\n<h2>Authentication without logging in every time</h2>\n<p>Most tests need a logged in user, and logging in through the form in every test is slow and tests the login screen hundreds of times. Log in once, save the browser state and reuse it:</p>\n<pre><code class=\"language-java\">static final Path AUTH_STATE = Paths.get(\"target/auth/ana.json\");\n\n@BeforeAll\nstatic void loginOnce() {\n    try (BrowserContext login = browser.newContext()) {\n        Page page = login.newPage();\n        page.navigate(baseUrl + \"/login\");\n        page.getByLabel(\"Email\").fill(\"ana@example.test\");\n        page.getByLabel(\"Password\").fill(\"correct horse battery\");\n        page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Sign in\")).click();\n        page.waitForURL(\"**/dashboard\");\n        login.storageState(new BrowserContext.StorageStateOptions().setPath(AUTH_STATE));\n    }\n}\n\n@BeforeEach\nvoid createAuthenticatedContext() {\n    context = browser.newContext(new Browser.NewContextOptions().setStorageStatePath(AUTH_STATE));\n    page = context.newPage();\n}</code></pre>\n<p><code>storageState</code> saves cookies and local storage to a JSON file, and a new context created from it starts already signed in. Keep the login scenario itself as one dedicated test that exercises the form. For token based APIs, authenticate with the <code>APIRequestContext</code> (below) and inject the token, which is faster still. The credentials are test data, created by the test setup and never real ones; store them in test configuration, not in source files that might be mistaken for production secrets.</p>\n<h2>Controlling the network</h2>\n<p>Playwright can intercept requests, which is useful in three ways. <strong>Stub an external call</strong> so the page does not depend on a third party:</p>\n<pre><code class=\"language-java\">page.route(\"**/api/exchange-rates\", route -&gt; route.fulfill(new Route.FulfillOptions()\n        .setStatus(200)\n        .setContentType(\"application/json\")\n        .setBody(\"{\\\"USD\\\": 1.0, \\\"VND\\\": 25000.0}\")));</code></pre>\n<p><strong>Simulate a failure</strong> to test error handling, which is hard to trigger otherwise:</p>\n<pre><code class=\"language-java\">page.route(\"**/api/orders\", route -&gt; route.fulfill(new Route.FulfillOptions().setStatus(503)));\npage.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Pay now\")).click();\nassertThat(page.getByText(\"We could not place your order. Please try again.\")).isVisible();</code></pre>\n<p><strong>Wait for a specific request</strong> when the assertion should follow an API call:</p>\n<pre><code class=\"language-java\">Response response = page.waitForResponse(\"**/api/orders\", () -&gt;\n        page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Pay now\")).click());\nassertThat(response.status()).isEqualTo(201);</code></pre>\n<p>Be sparing with stubbing: a test that stubs the entire back end tests only the front end, which is a legitimate component test, though not an end to end one. For the back end checks, an <code>APIRequestContext</code> makes HTTP calls with the same cookies as the browser context, so a test can set up or verify state through the API without the UI:</p>\n<pre><code class=\"language-java\">APIRequestContext api = playwright.request().newContext(new APIRequest.NewContextOptions().setBaseURL(baseUrl));\nAPIResponse created = api.post(\"/api/test/orders\", RequestOptions.create().setData(Map.of(\"sku\", \"BK-1\", \"qty\", 2)));\nassertThat(created.ok()).isTrue();</code></pre>\n<h2>Debugging: traces, screenshots and the inspector</h2>\n<p>A failing UI test in CI is useless without evidence. Playwright's best tool is the <strong>trace</strong>: a recording of every action with a DOM snapshot before and after, the network requests, the console and a timeline. Record one per test and keep it when the test fails:</p>\n<pre><code class=\"language-java\">@BeforeEach\nvoid startTracing() {\n    context.tracing().start(new Tracing.StartOptions().setScreenshots(true).setSnapshots(true).setSources(true));\n}\n\n@AfterEach\nvoid saveTraceOnFailure(TestInfo info, TestReporter reporter) {\n    boolean failed = /* determine from a TestWatcher extension */ testFailed;\n    context.tracing().stop(failed\n            ? new Tracing.StopOptions().setPath(Paths.get(\"target/traces/\" + info.getDisplayName() + \".zip\"))\n            : new Tracing.StopOptions());\n    context.close();\n}</code></pre>\n<p>Open a trace with the viewer, which shows the steps on the left and a time travelling DOM on the right:</p>\n<pre><code class=\"language-bash\">mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=\"show-trace target/traces/checkout.zip\"</code></pre>\n<p>Upload the <code>target/traces</code> folder as a CI artifact and a failed run becomes a replay. Determining pass or fail in <code>@AfterEach</code> needs a JUnit <code>TestWatcher</code> or <code>TestExecutionExceptionHandler</code> extension that records the outcome, covered in <a href=\"/library/junit-extension-model-5-explained\">the JUnit extension model</a>. Screenshots and video are simpler: <code>page.screenshot(new Page.ScreenshotOptions().setPath(...).setFullPage(true))</code> on failure, and <code>setRecordVideoDir(Paths.get(\"target/videos\"))</code> on the context options.</p>\n<p>For writing a test, the <strong>Inspector</strong> is the fastest route. Run with the environment variable <code>PWDEBUG=1</code> and the browser opens in step mode with a locator picker, and <code>page.pause()</code> in a test stops there so you can try locators live. The <code>codegen</code> tool records your clicks and prints Java code you can paste as a starting point:</p>\n<pre><code class=\"language-bash\">mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=\"codegen https://shop.example.test\"</code></pre>\n<p>Treat generated code as a draft: tidy the locators and move repeated steps into page objects.</p>\n<h2>Parallel execution and speed</h2>\n<p>A suite of fifty browser tests at fifteen seconds each is twelve minutes serially. Playwright tests are isolated by context, so they parallelise well, with the thread safety rule: one <code>Playwright</code> instance per thread. With JUnit 5, either configure parallel execution and give each thread its own <code>Playwright</code> and <code>Browser</code>, or fork the JVM in Surefire so each fork runs some test classes:</p>\n<pre data-filename=\"pom.xml\"><code class=\"language-xml\">&lt;plugin&gt;\n    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n    &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt;\n    &lt;configuration&gt;\n        &lt;forkCount&gt;4&lt;/forkCount&gt;\n        &lt;reuseForks&gt;true&lt;/reuseForks&gt;\n        &lt;includes&gt;&lt;include&gt;**/*E2ETest.java&lt;/include&gt;&lt;/includes&gt;\n    &lt;/configuration&gt;\n&lt;/plugin&gt;</code></pre>\n<p>Parallel tests must not share mutable state: a database fixture one test deletes breaks another that reads it. Give each test its own data (a unique email, its own tenant), as in <a href=\"/library/deterministic-tests-java-test-time-randomness\">deterministic tests with time and randomness</a>. Beyond parallelism, speed comes from fewer end to end tests: skip UI setup by seeding data directly, reuse authentication state, stub slow third parties and keep each test to one journey.</p>\n<h2>Continuous integration</h2>\n<p>A CI job needs the browsers and their system dependencies, headless mode and artifacts for failures. In GitHub Actions:</p>\n<pre data-filename=\".github/workflows/e2e.yml\"><code class=\"language-yaml\">name: e2e\non:\n  pull_request:\njobs:\n  e2e:\n    runs-on: ubuntu-latest\n    timeout-minutes: 20\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-java@v4\n        with:\n          distribution: temurin\n          java-version: 25\n          cache: maven\n      - name: Install browsers\n        run: mvn -B exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=\"install --with-deps chromium\"\n      - name: Run end to end tests\n        run: mvn -B verify -Pe2e\n      - uses: actions/upload-artifact@v4\n        if: failure()\n        with:\n          name: playwright-traces\n          path: target/traces</code></pre>\n<p>Docker is available on GitHub's hosted runners, so Testcontainers works. Cache the browser download directory (<code>~/.cache/ms-playwright</code>) to save a minute per run. Run the suite on pull requests for critical journeys and the full set nightly if it is large. Playwright also publishes Docker images with the browsers preinstalled (<code>mcr.microsoft.com/playwright/java</code>), which suit CI systems that build their own containers.</p>\n<h2>Iframes, popups, downloads and dialogs</h2>\n<p>Real applications have corners that a first tutorial skips, and Playwright handles each with a specific API instead of a workaround.</p>\n<p><strong>Iframes.</strong> Content inside an iframe is a separate document, reached through a <code>FrameLocator</code>. A payment widget embedded from a provider is the typical case:</p>\n<pre><code class=\"language-java\">FrameLocator card = page.frameLocator(\"iframe[name='card-fields']\");\ncard.getByLabel(\"Card number\").fill(\"4242424242424242\");\ncard.getByLabel(\"Expiry\").fill(\"12/30\");\ncard.getByLabel(\"CVC\").fill(\"123\");</code></pre>\n<p>The frame locator waits for the frame to load, like any locator waits for its element.</p>\n<p><strong>New tabs and popups.</strong> An action that opens a window returns it through an event, which you must listen for before triggering the action, or the event is missed:</p>\n<pre><code class=\"language-java\">Page popup = page.waitForPopup(() -&gt;\n        page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName(\"Terms and conditions\")).click());\nassertThat(popup.getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName(\"Terms\"))).isVisible();</code></pre>\n<p>The lambda passed to <code>waitForPopup</code> performs the action, and the call returns the new <code>Page</code> once it opens.</p>\n<p><strong>Downloads.</strong> The same pattern captures a file download, and you can check where it landed and what it contains:</p>\n<pre><code class=\"language-java\">Download download = page.waitForDownload(() -&gt;\n        page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(\"Export CSV\")).click());\nPath saved = download.path();\nassertThat(Files.readString(saved)).startsWith(\"order_id,customer,total\");\nassertThat(download.suggestedFilename()).isEqualTo(\"orders.csv\");</code></pre>\n<p><strong>Native dialogs.</strong> <code>alert</code>, <code>confirm</code> and <code>prompt</code> dialogs are dismissed automatically unless you register a handler. Register one before the action when the test must accept or inspect it:</p>\n<pre><code class=\"language-java\">page.onDialog(dialog -&gt; {\n    assertThat(dialog.message()).contains(\"Delete this order?\");\n    dialog.accept();\n});</code></pre>\n<p><strong>Clipboard, geolocation and permissions</strong> are granted per context (<code>context.grantPermissions(List.of(\"geolocation\"))</code>, <code>setGeolocation(...)</code>), which allows deterministic tests of features that normally prompt the user.</p>\n<h2>Walking through the design of one journey</h2>\n<p>It helps to see the decisions behind a single test, since the skill of end to end testing is mostly in choosing what to put in a test. Take the journey \"a returning customer reorders a previous purchase\". A first draft clicks through registration, shopping, checkout and then the reorder. That draft is slow, and a failure anywhere before the reorder tells you nothing about reordering.</p>\n<p>Redesign it by asking what the test is about. It is about the reorder feature, so everything before it is <strong>precondition</strong>, created directly: the test inserts a customer with a past order through the repository, loads the saved authentication state for that customer and opens the order history page. The browser then does only what the feature involves: find the past order, click \"Reorder\", check that the basket contains the same items and that the prices shown are the current prices, not the historic ones, and finish by paying. The result is a test that takes a few seconds, fails only when reordering is broken and reads as a description of the feature.</p>\n<p>The second decision is the assertion at the end. A UI check, \"thank you page visible\", is necessary and weak on its own; an application can show a thank you page and fail to create the order. The test also asks the database, through the test data helper, whether a new order exists for the customer with the expected lines, and whether a payment record was created through the stubbed gateway exactly once. The <strong>exactly once</strong> matters in a journey with retries and double clicks, and it is the sort of defect that only an end to end test with a real database can show.</p>\n<p>The third decision is what to leave out. The test does not check the footer, the header links or the exact wording of marketing text. Anything not about the journey would make the test fail for unrelated reasons, and the more assertions a test contains, the more reasons it has to fail. A test should fail for one reason, which should be the reason in its name.</p>\n<h2>Configuration per environment</h2>\n<p>The same tests are useful against several environments: the application started by the test itself, a shared staging deployment and, with care, a production smoke check. Parameterise the base URL and the browser, and keep secrets out of the code:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/e2e/E2eConfig.java\"><code class=\"language-java\">public final class E2eConfig {\n    private E2eConfig() {}\n\n    public static String baseUrl(int localPort) {\n        String configured = System.getProperty(\"e2e.baseUrl\", System.getenv(\"E2E_BASE_URL\"));\n        return configured != null ? configured : \"http://localhost:\" + localPort;\n    }\n\n    public static BrowserType browserType(Playwright playwright) {\n        return switch (System.getProperty(\"e2e.browser\", \"chromium\")) {\n            case \"firefox\" -&gt; playwright.firefox();\n            case \"webkit\" -&gt; playwright.webkit();\n            default -&gt; playwright.chromium();\n        };\n    }\n}</code></pre>\n<pre><code class=\"language-bash\">mvn verify -Pe2e -De2e.baseUrl=https://staging.example.test -De2e.browser=firefox</code></pre>\n<p>Running the critical journeys on all three engines nightly, and on Chromium for each pull request, catches the rare browser specific bug without tripling the cost of every build. Tests against a shared environment need extra care: use test accounts, unique data and cleanup, and never run destructive journeys against production.</p>\n<h2>Reading three typical failures</h2>\n<p>Knowing how failures look makes them quicker to fix.</p>\n<p><strong>The disabled button.</strong> The trace shows the click waiting on \"Pay now\" and the log says the element is not enabled. The usual cause is a form field that never became valid, because the test typed an invalid value or the form validates on blur and the test never left the field. The fix belongs in the test data or in a missing action such as <code>press(\"Tab\")</code>, not in a longer timeout.</p>\n<p><strong>The strict mode violation.</strong> The error lists several matching elements: a page with two \"Add to basket\" buttons, one in the product card and one in the recommendations strip. The locator was too broad. Scope it to the container that identifies the product, rather than taking <code>first()</code>, which would click the wrong one the day the layout changes.</p>\n<p><strong>The assertion that passes locally and fails in CI.</strong> The trace shows the page, in CI, rendering an empty list for two seconds before the data arrives, and the assertion <code>hasCount(12)</code> timed out at five. The CI machine is slower and the back end is cold. Two legitimate fixes: raise the assertion timeout in CI through configuration, or make the page show a loading state that the test can wait for. A third, tempting fix, <code>Thread.sleep(3000)</code>, hides the problem and slows every run.</p>\n<p>The common thread is that the evidence, a trace with DOM snapshots, answers the question \"what did the page look like at that moment\" without rerunning anything, which is why recording it is the first thing to set up.</p>\n<h2>Moving from Selenium</h2>\n<p>Teams with an existing Selenium suite often ask what the translation looks like. The concepts map one to one, the differences are in waiting and element handling:</p>\n<table><thead><tr><th>Selenium</th><th>Playwright for Java</th></tr></thead><tbody><tr><td><code>WebDriver driver = new ChromeDriver()</code></td><td><code>browser.newPage()</code> or a context's <code>newPage()</code></td></tr><tr><td><code>driver.findElement(By.id(\"email\")).sendKeys(\"x\")</code></td><td><code>page.getByLabel(\"Email\").fill(\"x\")</code></td></tr><tr><td><code>new WebDriverWait(driver, ...).until(visibilityOf(...))</code></td><td>Not needed; actions and <code>assertThat</code> wait</td></tr><tr><td><code>WebElement</code> (can go stale)</td><td><code>Locator</code> (re-resolved on each use)</td></tr><tr><td><code>driver.switchTo().frame(...)</code></td><td><code>page.frameLocator(...)</code></td></tr><tr><td><code>Actions</code> class for hover and drag</td><td><code>locator.hover()</code>, <code>locator.dragTo(...)</code></td></tr><tr><td>Selenium Grid</td><td>Run Playwright in parallel forks, or a hosted browser service</td></tr><tr><td>Implicit waits</td><td>Default action timeouts</td></tr></tbody></table>\n<p>Migrate incrementally. Write new tests in Playwright, move the flakiest Selenium tests first, since they gain the most from auto waiting and traces, and retire the old ones as journeys are covered. Run both in CI during the transition, and avoid translating line by line: a Selenium test full of explicit waits and page object workarounds is better rewritten from the user journey than mechanically converted.</p>\n<h2>Why browser tests flake, and the cures</h2>\n<p>Most flakiness has a known cause.</p>\n<table><thead><tr><th>Cause</th><th>Symptom</th><th>Cure</th></tr></thead><tbody><tr><td>Fixed sleeps</td><td>Pass on fast machines, fail on slow ones</td><td>Delete them; use auto waiting and web first assertions</td></tr><tr><td>Assertions that read once</td><td><code>assertEquals</code> on <code>textContent()</code> fails intermittently</td><td>Use <code>assertThat(locator)</code> that retries</td></tr><tr><td>Shared test data</td><td>A test fails only after another ran</td><td>Unique data per test; clean up in the test</td></tr><tr><td>Dependence on time or random values</td><td>Fails near midnight or on a different locale</td><td>Fix the clock in the application, set locale and time zone in the context</td></tr><tr><td>Animations and transitions</td><td>Clicks land on a moving element</td><td>Actionability checks handle it; disable animations in test mode if needed</td></tr><tr><td>Real third party calls</td><td>Fails when the vendor is slow</td><td>Stub at the network or server level</td></tr><tr><td>Ambiguous locators</td><td>Clicks the wrong element</td><td>Use role and name; scope with chaining</td></tr><tr><td>Order dependence</td><td>Passes alone, fails in the suite</td><td>Isolate state; run in random order</td></tr><tr><td>Resource starvation on CI</td><td>Timeouts only in CI</td><td>Fewer parallel forks, more CPU, longer action timeout in CI</td></tr></tbody></table>\n<p>Track flaky tests explicitly: a test that fails and passes on rerun is a bug report, and a policy of retrying it silently hides the bug. Set a retry of one in CI for diagnosis, and treat any test that needs it as broken. A longer treatment of the causes and fixes is in <a href=\"/library/flaky-tests-java-fix\">fixing flaky tests in Java</a>.</p>\n<h2>Accessibility checks and visual concerns</h2>\n<p>Because locators are role based, accessibility is partly tested for free. For a more systematic check, the axe engine can be injected into a page and its findings asserted, with a Java wrapper such as <code>axe-core</code> through <code>page.evaluate</code>, and failures reported with the selectors involved. Visual regression, comparing screenshots against a baseline, is available in the JavaScript test runner and is not built into the Java library; for Java teams, tools such as Percy or a screenshot comparison library fill the gap, with the usual cost of baselines that must be reviewed and updated. Emulate devices by context options for a viewport, user agent and touch support:</p>\n<pre><code class=\"language-java\">BrowserContext mobile = browser.newContext(new Browser.NewContextOptions()\n        .setViewportSize(390, 844)\n        .setDeviceScaleFactor(3)\n        .setIsMobile(true)\n        .setHasTouch(true)\n        .setUserAgent(\"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)\"));</code></pre>\n<h2>Test data that does not fight back</h2>\n<p>Most of the maintenance cost of an end to end suite lives in data. A few rules keep it manageable.</p>\n<p><strong>Create what the test needs, with names that cannot collide.</strong> Generate the identifying values: <code>\"ana-\" + UUID.randomUUID() + \"@example.test\"</code>. Two tests running at once, or a test rerun after a crash that did not clean up, then never meet. A fixed email such as <code>ana@example.test</code> works until the first rerun against a database that was not reset, and fails with a duplicate key that has nothing to do with the feature.</p>\n<p><strong>Build a small builder for the test data.</strong> A <code>TestData</code> class with methods like <code>customer()</code>, <code>product(name, price)</code> and <code>orderFor(customer, product)</code> makes fixtures a line each and gives you one place to change when a column is added. Back it with the application's repositories so it uses the real constraints, or with SQL scripts where speed matters most.</p>\n<pre><code class=\"language-java\">public record TestData(CustomerRepository customers, ProductRepository products, OrderRepository orders) {\n\n    public Customer customer() {\n        return customers.save(new Customer(\"ana-\" + UUID.randomUUID() + \"@example.test\", passwordEncoder.encode(\"correct horse\")));\n    }\n\n    public Order orderFor(Customer customer, Product... items) {\n        return orders.save(Order.paid(customer, items));\n    }\n}</code></pre>\n<p><strong>Decide how state is reset.</strong> A container per test class gives a clean database cheaply when the schema loads quickly. For a heavier schema, share one container and clean the tables the test touched in <code>@AfterEach</code>, or wrap each test in a database snapshot where the engine supports it. What you must avoid is a suite that passes only when run in a particular order against a database left dirty by earlier runs. Randomised order in CI exposes it early, which is why the JUnit setting <code>junit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer$Random</code> is worth turning on.</p>\n<p><strong>Keep time under control.</strong> Journeys that depend on dates, trial periods or schedules need a clock you can set. Expose a test only endpoint or a configuration hook that fixes the application clock, as in <a href=\"/library/replace-java-util-date-joda-time\">replacing java.util.Date with java.time and injecting a Clock</a>, and set the browser's time zone and locale in the context.</p>\n<h2>Keyboard and accessibility checks in the same suite</h2>\n<p>Because Playwright interacts with the page as a user does, it can verify the parts of accessibility that are about interaction without extra tooling. A form that works only with a mouse is a defect for keyboard users, and a short test finds it:</p>\n<pre><code class=\"language-java\">@Test\nvoid theLoginFormCanBeCompletedWithTheKeyboardOnly() {\n    page.navigate(baseUrl + \"/login\");\n\n    page.keyboard().press(\"Tab\");\n    assertThat(page.getByLabel(\"Email\")).isFocused();\n    page.keyboard().type(\"ana@example.test\");\n    page.keyboard().press(\"Tab\");\n    assertThat(page.getByLabel(\"Password\")).isFocused();\n    page.keyboard().type(\"correct horse battery\");\n    page.keyboard().press(\"Enter\");\n\n    assertThat(page).hasURL(Pattern.compile(\".*/dashboard\"));\n}</code></pre>\n<p>The test asserts the tab order and the submit on <code>Enter</code>, which are exactly the things that break when someone replaces a <code>&lt;button&gt;</code> with a styled <code>&lt;div&gt;</code>. Role based locators make a related check implicit: if <code>getByRole(BUTTON, name = \"Sign in\")</code> finds nothing, the element is not exposed to assistive technology as a button. For a broader automated scan, inject the axe-core script and evaluate it on the page, then assert that the list of violations is empty or matches an agreed baseline. Automated tools find a minority of accessibility problems, those with machine checkable rules such as missing labels and insufficient contrast, so treat the result as a floor, not a certification, and combine it with manual checks by someone who uses a screen reader.</p>\n<h2>Keeping the suite healthy over time</h2>\n<p>An end to end suite decays unless someone owns it. Four habits slow the decay.</p>\n<p>Review a test failure as a product question first: did the application break, or did the intended behaviour change? A deliberate redesign that breaks fifteen tests is the signal to have fewer, higher level tests, since tests that mirror the DOM structure break with every layout change while tests that follow user intent survive.</p>\n<p>Track the suite's health with numbers the team can see: total run time, failure rate per test over the last month and the list of tests that were retried. A test that fails once in twenty runs is costing more in distrust than it earns in coverage; fix it or delete it. Deleting a flaky test whose journey is covered elsewhere is a perfectly good outcome.</p>\n<p>Treat the page objects and helpers as production code in review. A page object with copy pasted locators, or a helper with a hidden sleep, spreads the same defect into every test that uses it.</p>\n<p>Budget the run time. Decide what the pull request pipeline can afford, perhaps ten minutes, and keep the pull request suite inside it by selecting the critical journeys, moving the rest to a nightly job. A suite that takes forty minutes stops being run before merging, and a suite nobody runs before merging does not protect anything.</p>\n<h2>Running against a deployed environment</h2>\n<p>Everything above starts the application inside the test, which gives the most control. Teams also run a small set of journeys against a deployed environment after each release, a <strong>smoke suite</strong>, to prove that the deployment, its configuration and its real dependencies work together. Three adjustments make that safe. Use dedicated test accounts and tenants, isolated from real customers, and mark their data so a cleanup job can remove it. Limit the suite to read mostly or reversible journeys, a login, a search, adding to a basket without paying, because a test that places real orders in a shared environment pollutes reports and can trigger real emails. And make the suite quick, under two minutes, since it sits on the critical path of the deployment: its job is to answer \"did the release break the front door\", not to repeat the regression suite. A failure should block the rollout or trigger an automatic rollback, which is only credible if the suite is reliable, which brings us back to the rules on flakiness above.</p>\n<h2>What belongs in an end to end suite</h2>\n<p>Browser tests are the most expensive tests you have: slow to run, costly to maintain and diagnose. Spend them on <strong>a handful of critical user journeys</strong>: sign up, sign in, the main purchase or core workflow, and any journey whose failure would be a business incident. Cover rules, calculations and edge cases below the browser, with unit tests for logic and <code>MockMvc</code> or API tests for the web layer, as in <a href=\"/library/spring-mockmvc-test-controllers\">testing controllers with MockMvc</a> and <a href=\"/library/rest-assured-use-api-tests\">testing REST APIs with REST Assured</a>. A useful ratio is hundreds of unit tests, dozens of integration tests and ten to thirty browser journeys. When a browser test fails, the investigation should start from a trace, and the fix often belongs to a lower layer: add the missing unit test, and the browser test stays as the safety net.</p>\n<p>A question teams ask: Playwright or Selenium? Selenium has the longest history, the widest language and grid ecosystem and the WebDriver standard behind it. Playwright's auto waiting, tracing, isolated contexts and a single API for three engines give a better experience for most new Java projects, with the trade-offs that its browser builds are Playwright's own patched versions and its ecosystem for large scale grid execution is younger. Existing Selenium suites that work are rarely worth rewriting; new suites should start with Playwright.</p>\n<h2>A checklist for a suite you can trust</h2>\n<ol><li>Locators use roles, labels and text; test ids only where nothing else works.</li><li>No sleeps, anywhere. Assertions that read page state use <code>assertThat(locator)</code>.</li><li>One browser per class, a fresh context per test, fixed locale, time zone and viewport.</li><li>Test data created through code or API, unique per test, never through the UI unless that is the test.</li><li>External services stubbed; the database real and disposable.</li><li>Authentication state reused; one test for the login form itself.</li><li>Traces recorded and uploaded when a test fails; flaky tests treated as defects.</li><li>Suite size controlled: critical journeys only, with the detail below the browser.</li></ol>\n<h2>A last word on ownership</h2>\n<p>A browser test suite stays healthy when someone owns it. Name an owner for the suite, review new tests in the same pull requests as the features they cover and delete tests when the feature goes. Treat a test that has to be rerun as an open defect with a due date. These habits cost little and are the difference between a suite the team trusts and one that gets switched off after the third false alarm.</p>\n<h2>When this does not apply</h2>\n<p>If the application is a pure API with no front end, browser tests have no role, and API tests carry the weight. If the front end is a small amount of server rendered HTML with no JavaScript, a <code>MockMvc</code> plus HTML assertion test may give most of the value at a fraction of the cost. For teams whose front end is developed in JavaScript, the front end repository's own Playwright tests (in TypeScript) are likely to be where end to end tests live, and the Java suite can focus on the back end. For the primary references, read the <a href=\"https://playwright.dev/java/docs/intro\">Playwright for Java documentation</a>, the <a href=\"https://playwright.dev/java/docs/best-practices\">guidance on best practices</a> and the <a href=\"https://playwright.dev/java/docs/trace-viewer\">trace viewer guide</a>.</p>","date_published":"2026-11-14T04:14:31+00:00","tags":["Testing"]},{"id":"https://javahacks.dev/library/spring-data-jpa-query-specification-write","url":"https://javahacks.dev/library/spring-data-jpa-query-specification-write","title":"Spring Data JPA Custom Queries Guide With Examples","summary":"A complete guide to custom queries in Spring Data JPA: derived queries, JPQL and native SQL, paging, Specifications, fragments, streaming and tests.","content_html":"<p>Every Spring Data JPA project starts with the same pleasant surprise: declare an interface, write <code>findByEmail</code>, and the query exists. The pleasure lasts until the first requirement that a method name cannot carry, a search with six optional filters, a report that joins four tables, a query that needs a database specific feature or a bulk update. At that point developers discover that Spring Data has a whole ladder of tools for custom queries, and that choosing the right rung matters: the wrong one produces unreadable method names, queries that load a million rows into memory or code that is easy to break with a string concatenation. This guide walks the ladder from the bottom: derived queries, <code>@Query</code> with JPQL, paging and sorting, native SQL, named queries, projections, <code>Specification</code>s for dynamic filters, custom repository fragments, locking and hints, streaming large results, safety against injection and testing. Each section has code against one small domain, with the SQL it produces. It uses Spring Boot 4, Spring Data JPA and Hibernate 7 on PostgreSQL, and the examples are meant to be copied.</p>\n<p>The idea to carry through: <strong>a repository method is a query with a name and a return type, and the work is choosing the cheapest way to write it that stays readable and fast.</strong> For single issues, the companion posts are <a href=\"/library/spring-data-jpa-projections-use-fetch\">using projections to fetch less</a>, <a href=\"/library/jpa-criteria-api-use-dynamic-queries\">the Criteria API for dynamic queries</a> and <a href=\"/library/jpa-bulk-update-delete-updates-deletes\">bulk updates and deletes</a>.</p>\n<h2>The domain</h2>\n<p>The examples use customers, orders and order lines:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/Customer.java\"><code class=\"language-java\">@Entity\npublic class Customer {\n    @Id @GeneratedValue private Long id;\n\n    @Column(nullable = false, unique = true)\n    private String email;\n\n    private String name;\n    private String country;\n    private boolean active = true;\n\n    // constructors, getters and setters omitted\n}</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/Order.java\"><code class=\"language-java\">@Entity\n@Table(name = \"orders\")\npublic class Order {\n    @Id @GeneratedValue private Long id;\n\n    @ManyToOne(fetch = FetchType.LAZY, optional = false)\n    private Customer customer;\n\n    @Enumerated(EnumType.STRING)\n    private OrderStatus status;\n\n    private BigDecimal total;\n    private Instant placedAt;\n\n    @OneToMany(mappedBy = \"order\", cascade = CascadeType.ALL)\n    private List&lt;OrderLine&gt; lines = new ArrayList&lt;&gt;();\n\n    // constructors, getters and setters omitted\n}\n\npublic enum OrderStatus { NEW, PAID, SHIPPED, CANCELLED }</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/OrderLine.java\"><code class=\"language-java\">@Entity\npublic class OrderLine {\n    @Id @GeneratedValue private Long id;\n\n    @ManyToOne(fetch = FetchType.LAZY, optional = false)\n    private Order order;\n\n    private String sku;\n    private int quantity;\n    private BigDecimal unitPrice;\n}</code></pre>\n<h2>The ladder at a glance</h2>\n<table><thead><tr><th>Technique</th><th>Write</th><th>Best for</th><th>Limits</th></tr></thead><tbody><tr><td>Derived query</td><td>A method name</td><td>Simple lookups on one or two properties</td><td>Long names, no custom joins or functions</td></tr><tr><td><code>@Query</code> (JPQL)</td><td>A query string</td><td>Joins, aggregates, custom conditions</td><td>Static: the shape is fixed at compile time</td></tr><tr><td><code>@Query</code> (native)</td><td>SQL</td><td>Database features, hand tuned queries</td><td>Ties to one database, weaker type safety</td></tr><tr><td>Named query</td><td>JPQL on the entity</td><td>Reusing a query; validated at startup</td><td>Away from the repository, more indirection</td></tr><tr><td><code>Specification</code></td><td>Java predicates</td><td>Dynamic filters from user input</td><td>More code; not for fixed queries</td></tr><tr><td>Custom fragment</td><td>A class using <code>EntityManager</code></td><td>Anything else: Criteria, jOOQ, Querydsl, bulk logic</td><td>You write and test the whole thing</td></tr><tr><td>Query by Example</td><td>An entity as a probe</td><td>Simple search by example fields</td><td>Limited operators</td></tr></tbody></table>\n<p>Move up the ladder only when the rung below stops being readable.</p>\n<h2>Rung 1: derived queries</h2>\n<p>Spring Data parses the method name into a query. The grammar is <code>find...By</code> followed by property names and keywords, and the keywords map to JPQL operators:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/CustomerRepository.java\"><code class=\"language-java\">public interface CustomerRepository extends JpaRepository&lt;Customer, Long&gt; {\n\n    Optional&lt;Customer&gt; findByEmailIgnoreCase(String email);\n\n    List&lt;Customer&gt; findByCountryAndActiveTrueOrderByNameAsc(String country);\n\n    List&lt;Customer&gt; findByNameContainingIgnoreCase(String fragment);\n\n    List&lt;Customer&gt; findByCountryIn(Collection&lt;String&gt; countries);\n\n    boolean existsByEmail(String email);\n\n    long countByActiveTrue();\n\n    List&lt;Customer&gt; findTop10ByActiveTrueOrderByIdDesc();\n\n    void deleteByActiveFalse();\n}</code></pre>\n<table><thead><tr><th>Keyword</th><th>Produces</th><th>Example</th></tr></thead><tbody><tr><td><code>And</code>, <code>Or</code></td><td>Boolean combination</td><td><code>findByCountryAndActive</code></td></tr><tr><td><code>Is</code>, <code>Equals</code> (default)</td><td><code>=</code></td><td><code>findByEmail</code></td></tr><tr><td><code>Not</code></td><td><code>&lt;&gt;</code></td><td><code>findByStatusNot</code></td></tr><tr><td><code>LessThan</code>, <code>GreaterThanEqual</code>, <code>Between</code></td><td>Comparison</td><td><code>findByTotalBetween</code></td></tr><tr><td><code>Like</code>, <code>Containing</code>, <code>StartingWith</code>, <code>EndingWith</code></td><td><code>like</code> with wildcards added</td><td><code>findByNameContaining</code></td></tr><tr><td><code>In</code>, <code>NotIn</code></td><td><code>in (...)</code></td><td><code>findByCountryIn</code></td></tr><tr><td><code>True</code>, <code>False</code></td><td>Boolean flag</td><td><code>findByActiveTrue</code></td></tr><tr><td><code>IsNull</code>, <code>IsNotNull</code></td><td>Null check</td><td><code>findByNameIsNull</code></td></tr><tr><td><code>IgnoreCase</code></td><td><code>upper(...)</code> on both sides</td><td><code>findByEmailIgnoreCase</code></td></tr><tr><td><code>OrderBy...Asc/Desc</code></td><td>Sorting</td><td><code>findByActiveTrueOrderByNameAsc</code></td></tr><tr><td><code>Top</code>, <code>First</code></td><td>Limit</td><td><code>findTop10By...</code></td></tr><tr><td><code>Distinct</code></td><td><code>select distinct</code></td><td><code>findDistinctByCountry</code></td></tr><tr><td><code>exists...By</code>, <code>count...By</code>, <code>delete...By</code></td><td>Other operations</td><td><code>existsByEmail</code></td></tr></tbody></table>\n<p>Property paths traverse relationships with underscores or camel case: <code>findByCustomerEmail(String email)</code> on <code>Order</code> joins to <code>customer</code> and filters on its email. Spring Data resolves <code>CustomerEmail</code> greedily, first as a property <code>customerEmail</code>, then as <code>customer.email</code>; when an entity has a property that makes it ambiguous, use the underscore: <code>findByCustomer_Email</code>.</p>\n<p>Derived queries are excellent for what they do, and have three limits. Method names grow unreadable past three conditions: <code>findByCountryAndActiveTrueAndNameContainingIgnoreCaseAndCreatedAtAfterOrderByNameAsc</code> is a query nobody reviews carefully. A typo in a property name fails at startup (<code>No property 'contry' found for type 'Customer'</code>), which is a feature: the application will not start with a broken derived query. And <code>deleteBy...</code> loads each entity and deletes it individually, so it is not a bulk delete, as noted in <a href=\"/library/jpa-bulk-update-delete-updates-deletes\">bulk updates and deletes</a>.</p>\n<p>Return types decide behaviour: <code>Optional&lt;T&gt;</code> for at most one result (throwing <code>IncorrectResultSizeDataAccessException</code> if there are several), <code>List&lt;T&gt;</code>, <code>Stream&lt;T&gt;</code>, <code>Page&lt;T&gt;</code>, <code>Slice&lt;T&gt;</code>, <code>long</code> for counts and <code>boolean</code> for existence. A <code>T</code> return with no result gives <code>null</code>, which is why <code>Optional</code> is preferred.</p>\n<h2>Rung 2: @Query with JPQL</h2>\n<p>When the name stops being readable, write the query:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/OrderRepository.java\"><code class=\"language-java\">public interface OrderRepository extends JpaRepository&lt;Order, Long&gt;, JpaSpecificationExecutor&lt;Order&gt; {\n\n    @Query(\"\"\"\n            select o from Order o\n            where o.customer.country = :country\n              and o.status = :status\n              and o.total &gt;= :minTotal\n            order by o.placedAt desc\n            \"\"\")\n    List&lt;Order&gt; findBigOrders(@Param(\"country\") String country,\n                              @Param(\"status\") OrderStatus status,\n                              @Param(\"minTotal\") BigDecimal minTotal);\n\n    @Query(\"select o from Order o join fetch o.customer where o.id = :id\")\n    Optional&lt;Order&gt; findWithCustomer(@Param(\"id\") Long id);\n\n    @Query(\"select o.status, count(o), sum(o.total) from Order o group by o.status\")\n    List&lt;Object[]&gt; totalsByStatus();\n}</code></pre>\n<p>JPQL is the object query language: it queries entities and properties, not tables and columns, and Hibernate translates it to SQL. Text blocks keep multi line queries readable. Hibernate validates every <code>@Query</code> at <strong>startup</strong>, so a wrong property name fails when the application boots, not when someone calls the method.</p>\n<p><strong>Named parameters</strong> (<code>:country</code>) with <code>@Param</code> are the clear choice. Positional parameters (<code>?1</code>) work and are easy to misorder. Spring Boot's compiler flag <code>-parameters</code> lets you omit <code>@Param</code>, since the names are available, but being explicit costs nothing and survives a build setting change.</p>\n<p><strong>Operators and functions.</strong> JPQL supports <code>like</code>, <code>between</code>, <code>in</code>, <code>is null</code>, <code>member of</code>, <code>exists</code>, subqueries, <code>case when</code>, <code>coalesce</code>, <code>concat</code>, <code>lower</code>, <code>upper</code>, <code>length</code>, date functions and, in Hibernate 6 and later through HQL, window functions and CTEs. A <code>like</code> with a user supplied fragment needs the wildcards added in the caller or the query:</p>\n<pre><code class=\"language-java\">@Query(\"select c from Customer c where lower(c.name) like lower(concat('%', :fragment, '%'))\")\nList&lt;Customer&gt; search(@Param(\"fragment\") String fragment);</code></pre>\n<p><strong>Joins.</strong> A plain <code>join</code> filters; a <code>join fetch</code> also loads the association into the entity in the same query, which fixes N plus 1 for that use but must be handled with care (see paging below):</p>\n<pre><code class=\"language-java\">@Query(\"select distinct o from Order o join fetch o.lines where o.status = :status\")\nList&lt;Order&gt; findWithLines(@Param(\"status\") OrderStatus status);</code></pre>\n<p><code>distinct</code> removes the duplicate <code>Order</code> rows the join produces, one per line; Hibernate 6 and later de-duplicates root entities automatically, but the keyword documents intent and does not hurt.</p>\n<p><strong>Constructor expressions and projections</strong> select just the fields you need:</p>\n<pre><code class=\"language-java\">@Query(\"select new dev.javahacks.shop.OrderRow(o.id, c.name, o.total) from Order o join o.customer c where o.status = :status\")\nList&lt;OrderRow&gt; rows(@Param(\"status\") OrderStatus status);</code></pre>\n<p>with <code>public record OrderRow(Long id, String customerName, BigDecimal total) {}</code>, the DTO approach described in <a href=\"/library/spring-data-jpa-projections-use-fetch\">using projections</a>.</p>\n<p><strong>SpEL in queries.</strong> Spring Data lets a query reference method parameters and the entity name with SpEL, <code>#{#entityName}</code> for generic repositories and <code>:#{#filter.country}</code> to read a property from an object parameter:</p>\n<pre><code class=\"language-java\">@Query(\"select o from Order o where o.customer.country = :#{#filter.country} and o.total &gt;= :#{#filter.minTotal}\")\nList&lt;Order&gt; byFilter(@Param(\"filter\") OrderFilter filter);</code></pre>\n<p>Useful in moderation; heavy SpEL is untestable and hard to read.</p>\n<h2>Paging and sorting</h2>\n<p>Add a <code>Pageable</code> parameter and return a <code>Page</code>, and Spring Data adds <code>limit</code> and <code>offset</code> and runs a count query:</p>\n<pre><code class=\"language-java\">@Query(\"select o from Order o where o.status = :status\")\nPage&lt;Order&gt; findByStatus(@Param(\"status\") OrderStatus status, Pageable pageable);</code></pre>\n<pre><code class=\"language-java\">Page&lt;Order&gt; page = orders.findByStatus(OrderStatus.NEW, PageRequest.of(0, 20, Sort.by(\"placedAt\").descending()));\npage.getContent();         // the 20 rows\npage.getTotalElements();   // from the count query\npage.getTotalPages();</code></pre>\n<p>Three pitfalls. <strong>The count query is derived from the main query</strong>, and for a complex one the derivation can be wrong or slow. Supply your own:</p>\n<pre><code class=\"language-java\">@Query(value = \"select o from Order o join o.customer c where c.country = :country\",\n       countQuery = \"select count(o) from Order o join o.customer c where c.country = :country\")\nPage&lt;Order&gt; findByCountry(@Param(\"country\") String country, Pageable pageable);</code></pre>\n<p>**A <code>join fetch</code> of a collection with paging is a trap.** The database cannot limit rows of a joined collection, so Hibernate loads all rows and paginates in memory, logging <code>HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory</code>. On a large table this reads everything. The fix is two steps: page the ids or the root entities first, then load the associations for that page with a second query:</p>\n<pre><code class=\"language-java\">@Query(\"select o.id from Order o where o.status = :status\")\nPage&lt;Long&gt; pageIds(@Param(\"status\") OrderStatus status, Pageable pageable);\n\n@Query(\"select distinct o from Order o join fetch o.lines where o.id in :ids\")\nList&lt;Order&gt; findWithLines(@Param(\"ids\") Collection&lt;Long&gt; ids);</code></pre>\n<p><strong>Sorting by a user supplied property is an injection risk</strong> if it is passed into a native query or <code>JpaSort.unsafe</code>; validate against an allow list of sortable fields, as covered below.</p>\n<p>For infinite scroll and \"next page\" screens, return <code>Slice&lt;T&gt;</code>: it fetches one extra row to learn whether another page exists and skips the count query, which on a large table is often the most expensive part of paging. For very deep pages, offset paging gets slower with the offset; keyset (cursor) pagination, <code>where id &gt; :lastId order by id limit :n</code>, stays fast, as in cursor pagination in Spring Boot APIs.</p>\n<h2>Modifying queries</h2>\n<p>A query that changes data needs <code>@Modifying</code>, and the persistence context needs managing, since the statement bypasses it:</p>\n<pre><code class=\"language-java\">@Modifying(clearAutomatically = true, flushAutomatically = true)\n@Query(\"update Order o set o.status = :to where o.status = :from and o.placedAt &lt; :cutoff\")\nint expire(@Param(\"from\") OrderStatus from, @Param(\"to\") OrderStatus to, @Param(\"cutoff\") Instant cutoff);</code></pre>\n<p>The method returns the number of rows affected. The full set of consequences, stale entities, no cascades, no version increment, is in the bulk updates post; the short rule is to treat bulk statements as outside the entity model.</p>\n<h2>Rung 3: native queries</h2>\n<p>Use native SQL when you need what JPQL cannot express: database specific functions, <code>jsonb</code> operators, full text search, recursive CTEs written by hand, optimiser hints or a query tuned by a DBA:</p>\n<pre><code class=\"language-java\">@Query(value = \"\"\"\n        select c.country as country, count(*) as orders, sum(o.total) as revenue\n        from orders o join customer c on c.id = o.customer_id\n        where o.placed_at &gt;= :since\n        group by c.country\n        order by revenue desc\n        \"\"\", nativeQuery = true)\nList&lt;CountryRevenue&gt; revenueByCountry(@Param(\"since\") Instant since);\n\npublic interface CountryRevenue {\n    String getCountry();\n    long getOrders();\n    BigDecimal getRevenue();\n}</code></pre>\n<p>The aliases (<code>as country</code>) are the contract with the interface projection's getters. A native query returning entities selects <code>o.*</code> and lets Hibernate map the columns. Costs to know: the query is tied to one database engine, a column rename is not found by the compiler or at startup (the error comes when the method is first called), <code>Sort</code> from a <code>Pageable</code> is not applied to a native query automatically, and paging needs an explicit <code>countQuery</code>:</p>\n<pre><code class=\"language-java\">@Query(value = \"select * from orders where status = :status\",\n       countQuery = \"select count(*) from orders where status = :status\",\n       nativeQuery = true)\nPage&lt;Order&gt; nativeByStatus(@Param(\"status\") String status, Pageable pageable);</code></pre>\n<p>Use native queries for the few places that need them, and keep the SQL in text blocks next to a test.</p>\n<h2>Named queries</h2>\n<p>A named query is declared on the entity, with the name <code>Entity.method</code>, and Spring Data uses it for a repository method of that name without any annotation:</p>\n<pre><code class=\"language-java\">@Entity\n@NamedQuery(name = \"Order.findShippedBetween\",\n        query = \"select o from Order o where o.status = 'SHIPPED' and o.placedAt between :from and :to\")\npublic class Order { /* ... */ }</code></pre>\n<pre><code class=\"language-java\">List&lt;Order&gt; findShippedBetween(@Param(\"from\") Instant from, @Param(\"to\") Instant to);</code></pre>\n<p>Named queries are validated at startup, can be reused from non Spring code and keep long queries out of the repository interface. Most teams prefer <code>@Query</code> because the query sits beside the method that uses it, which is easier to read and refactor.</p>\n<h2>Rung 4: Specifications for dynamic filters</h2>\n<p>A search screen with optional filters cannot be a fixed query, as the combinations explode. A <code>Specification</code> is a reusable predicate builder over the Criteria API; extend <code>JpaSpecificationExecutor</code> on the repository, as above, and build specs:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/OrderSpecs.java\"><code class=\"language-java\">public final class OrderSpecs {\n    private OrderSpecs() {}\n\n    public static Specification&lt;Order&gt; hasStatus(OrderStatus status) {\n        return (root, query, cb) -&gt; status == null ? null : cb.equal(root.get(\"status\"), status);\n    }\n\n    public static Specification&lt;Order&gt; totalAtLeast(BigDecimal min) {\n        return (root, query, cb) -&gt; min == null ? null : cb.greaterThanOrEqualTo(root.get(\"total\"), min);\n    }\n\n    public static Specification&lt;Order&gt; placedBetween(Instant from, Instant to) {\n        return (root, query, cb) -&gt; {\n            List&lt;Predicate&gt; parts = new ArrayList&lt;&gt;();\n            if (from != null) parts.add(cb.greaterThanOrEqualTo(root.get(\"placedAt\"), from));\n            if (to != null) parts.add(cb.lessThan(root.get(\"placedAt\"), to));\n            return parts.isEmpty() ? null : cb.and(parts.toArray(Predicate[]::new));\n        };\n    }\n\n    public static Specification&lt;Order&gt; customerInCountry(String country) {\n        return (root, query, cb) -&gt; country == null ? null : cb.equal(root.join(\"customer\").get(\"country\"), country);\n    }\n}</code></pre>\n<pre><code class=\"language-java\">public Page&lt;Order&gt; search(OrderFilter f, Pageable pageable) {\n    Specification&lt;Order&gt; spec = Specification\n            .where(OrderSpecs.hasStatus(f.status()))\n            .and(OrderSpecs.totalAtLeast(f.minTotal()))\n            .and(OrderSpecs.placedBetween(f.from(), f.to()))\n            .and(OrderSpecs.customerInCountry(f.country()));\n    return orders.findAll(spec, pageable);\n}</code></pre>\n<p>A specification that returns <code>null</code> contributes no condition, so absent filters vanish from the SQL. <code>findAll(spec, pageable)</code> runs the data and count queries and honours the pageable's sort. For type safe attribute names, generate the static metamodel (<code>Order_.status</code>) with the Hibernate processor, as described in <a href=\"/library/jpa-criteria-api-use-dynamic-queries\">the Criteria API post</a>, so a rename fails the build. Joins inside specifications to collections multiply rows and break paging; filter with <code>exists</code> subqueries instead.</p>\n<h2>Rung 5: custom repository fragments</h2>\n<p>When none of the above fits, write the query yourself and still expose it on the repository. A <strong>fragment</strong> is an interface plus an implementation class named <code>...Impl</code>, which Spring Data composes into the repository:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/OrderReports.java\"><code class=\"language-java\">public interface OrderReports {\n    List&lt;MonthlyRevenue&gt; revenueByMonth(int year);\n}</code></pre>\n<pre data-filename=\"src/main/java/dev/javahacks/shop/OrderReportsImpl.java\"><code class=\"language-java\">class OrderReportsImpl implements OrderReports {\n\n    @PersistenceContext\n    private EntityManager em;\n\n    @Override\n    public List&lt;MonthlyRevenue&gt; revenueByMonth(int year) {\n        return em.createQuery(\"\"\"\n                        select new dev.javahacks.shop.MonthlyRevenue(month(o.placedAt), sum(o.total))\n                        from Order o\n                        where year(o.placedAt) = :year and o.status &lt;&gt; 'CANCELLED'\n                        group by month(o.placedAt)\n                        order by month(o.placedAt)\n                        \"\"\", MonthlyRevenue.class)\n                .setParameter(\"year\", year)\n                .getResultList();\n    }\n}</code></pre>\n<pre><code class=\"language-java\">public interface OrderRepository extends JpaRepository&lt;Order, Long&gt;, JpaSpecificationExecutor&lt;Order&gt;, OrderReports {\n}</code></pre>\n<p>The <code>Impl</code> suffix is how Spring Data finds the implementation: the fragment interface name plus <code>Impl</code>. Callers use <code>orders.revenueByMonth(2026)</code> and never know where it comes from. A fragment is the right home for queries built with Criteria directly, with Querydsl or jOOQ, with batching logic or with anything that needs the <code>EntityManager</code>. It is plain Java and plain testable code. Keep the fragments small and focused, one concern each, and compose several into a repository.</p>\n<h2>Query by Example</h2>\n<p>For a simple search where the search form mirrors the entity, Query by Example uses an entity instance as the probe:</p>\n<pre><code class=\"language-java\">Customer probe = new Customer();\nprobe.setCountry(\"VN\");\nprobe.setActive(true);\n\nExampleMatcher matcher = ExampleMatcher.matching()\n        .withIgnoreNullValues()\n        .withMatcher(\"name\", match -&gt; match.contains().ignoreCase());\n\nList&lt;Customer&gt; found = customers.findAll(Example.of(probe, matcher));</code></pre>\n<p>It is compact and limited: only equality and string matching, no ranges or joins, and it works only for properties of the entity. Good for admin screens; once you need a range, move to specifications.</p>\n<h2>Locking, hints and fetch graphs</h2>\n<p>Queries can carry JPA options as annotations:</p>\n<pre><code class=\"language-java\">@Lock(LockModeType.PESSIMISTIC_WRITE)\n@QueryHints(@QueryHint(name = \"jakarta.persistence.lock.timeout\", value = \"3000\"))\n@Query(\"select o from Order o where o.id = :id\")\nOptional&lt;Order&gt; lockForUpdate(@Param(\"id\") Long id);\n\n@EntityGraph(attributePaths = {\"customer\", \"lines\"})\nList&lt;Order&gt; findByStatus(OrderStatus status);\n\n@QueryHints(@QueryHint(name = \"org.hibernate.readOnly\", value = \"true\"))\nList&lt;Order&gt; findAllByStatus(OrderStatus status);</code></pre>\n<p><code>@Lock</code> takes a lock mode, covered in <a href=\"/library/jpa-pessimistic-locking-use\">pessimistic locking in JPA</a>. <code>@EntityGraph</code> declares which associations to fetch for a derived query without writing a join. The Hibernate <code>readOnly</code> hint skips dirty checking snapshots for entities that will not change, a small gain for large reads. Hints are provider specific strings; keep them in constants.</p>\n<h2>Streaming large results</h2>\n<p>A <code>List</code> of a million entities exhausts memory. Return a <code>Stream</code> and process rows one at a time, inside a transaction, closing the stream:</p>\n<pre><code class=\"language-java\">@QueryHints(@QueryHint(name = \"org.hibernate.fetchSize\", value = \"1000\"))\n@Query(\"select o from Order o where o.status = :status\")\nStream&lt;Order&gt; streamByStatus(@Param(\"status\") OrderStatus status);</code></pre>\n<pre><code class=\"language-java\">@Transactional(readOnly = true)\npublic void export(OutputStream out) {\n    try (Stream&lt;Order&gt; stream = orders.streamByStatus(OrderStatus.SHIPPED)) {\n        stream.forEach(order -&gt; {\n            write(out, order);\n            entityManager.detach(order);         // release it from the persistence context as you go\n        });\n    }\n}</code></pre>\n<p>Three conditions make it work: an open transaction (the stream is lazy and needs the connection), closing the stream (try with resources) and a driver configured to stream, which on PostgreSQL requires a fetch size and autocommit off. Detaching each entity stops the persistence context from accumulating every row. For truly huge exports, a stateless session or plain JDBC is lighter, see <a href=\"/library/hibernate-statelesssession-use-bulk-work\">Hibernate StatelessSession for bulk work</a>.</p>\n<h2>Safety: parameters, sorting and LIKE</h2>\n<p>Parameter binding is what makes Spring Data queries safe from SQL injection: a <code>:name</code> placeholder sends the value separately from the SQL text. The ways people still break it:</p>\n<p><strong>String concatenation into a native query</strong> built in a fragment:</p>\n<pre><code class=\"language-java\">em.createNativeQuery(\"select * from customer where name = '\" + name + \"'\");    // injectable: never do this</code></pre>\n<p>Always use <code>setParameter</code>.</p>\n<p><strong>Dynamic sorting.</strong> A <code>Sort</code> from request parameters (<code>?sort=name,desc</code>) is bound by Spring Data to property names validated against the entity, which is safe for derived and JPQL queries; for native queries, or <code>JpaSort.unsafe(...)</code>, the property name is placed into the SQL. Validate against an allow list:</p>\n<pre><code class=\"language-java\">private static final Set&lt;String&gt; SORTABLE = Set.of(\"placedAt\", \"total\", \"status\");\n\nSort safe(Sort requested) {\n    List&lt;Sort.Order&gt; allowed = requested.stream().filter(o -&gt; SORTABLE.contains(o.getProperty())).toList();\n    return allowed.isEmpty() ? Sort.by(\"placedAt\").descending() : Sort.by(allowed);\n}</code></pre>\n<p><strong>LIKE wildcards.</strong> A user typing <code>%</code> or <code>_</code> in a search box changes the pattern. Escape them if literal matching matters:</p>\n<pre><code class=\"language-java\">String escaped = fragment.replace(\"\\\\\", \"\\\\\\\\\").replace(\"%\", \"\\\\%\").replace(\"_\", \"\\\\_\");</code></pre>\n<p>and name the backslash as the escape character in the query's like clause.</p>\n<p><strong>Reflecting field names from input.</strong> A generic filter such as <code>?filter[name]=...</code> that builds specifications from arbitrary field names lets callers probe any column; whitelist the fields.</p>\n<h2>Check the SQL and the statement count</h2>\n<p>Every query that serves real traffic deserves a look at what actually ran. Turn on SQL logging in development, and measure statement counts in tests:</p>\n<pre><code class=\"language-properties\">spring.jpa.show-sql=false\nlogging.level.org.hibernate.SQL=DEBUG\nlogging.level.org.hibernate.orm.jdbc.bind=TRACE</code></pre>\n<pre><code class=\"language-text\">select o1_0.id,o1_0.placed_at,o1_0.status,o1_0.total,o1_0.customer_id from orders o1_0\njoin customer c1_0 on c1_0.id=o1_0.customer_id where c1_0.country=? and o1_0.status=? order by o1_0.placed_at desc</code></pre>\n<p>Read the SQL for the join type, the columns selected, the presence of a <code>limit</code> and the count query. Then run the slow ones through <code>explain analyze</code> on realistic data, as in <a href=\"/library/slow-query-java-explain-read-plan\">reading a slow query plan</a>, and check that the filter columns are indexed. A query that is fast on 1,000 rows and slow on 10 million is the usual story, and a derived method name hides how heavy it is. Count statements per request with Hibernate statistics, <a href=\"/library/hibernate-log-sql-statistics-count-statements\">as shown here</a>, to catch the N plus 1 that a <code>findAll()</code> followed by a getter on each row produces.</p>\n<h2>Test every query</h2>\n<p>A custom query is code that can be wrong in ways the compiler and startup validation do not see: a missing condition, the wrong join type, an off by one on a date range, an ordering that is not stable. Test each against a real database of the same type as production, using <code>@DataJpaTest</code> with Testcontainers:</p>\n<pre data-filename=\"src/test/java/dev/javahacks/shop/OrderRepositoryTest.java\"><code class=\"language-java\">@DataJpaTest\n@Testcontainers\n@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)\nclass OrderRepositoryTest {\n\n    @Container\n    @ServiceConnection\n    static PostgreSQLContainer&lt;?&gt; db = new PostgreSQLContainer&lt;&gt;(\"postgres:17\");\n\n    @Autowired OrderRepository orders;\n    @Autowired CustomerRepository customers;\n    @Autowired TestEntityManager em;\n\n    @Test\n    void findBigOrdersFiltersByCountryStatusAndTotal() {\n        Customer vn = customers.save(new Customer(\"ana@example.test\", \"Ana\", \"VN\"));\n        Customer us = customers.save(new Customer(\"bob@example.test\", \"Bob\", \"US\"));\n        orders.save(order(vn, OrderStatus.PAID, \"500.00\", \"2026-10-01T00:00:00Z\"));\n        orders.save(order(vn, OrderStatus.PAID, \"50.00\", \"2026-10-02T00:00:00Z\"));       // too small\n        orders.save(order(vn, OrderStatus.NEW, \"900.00\", \"2026-10-03T00:00:00Z\"));       // wrong status\n        orders.save(order(us, OrderStatus.PAID, \"900.00\", \"2026-10-04T00:00:00Z\"));      // wrong country\n        em.flush();\n        em.clear();\n\n        List&lt;Order&gt; result = orders.findBigOrders(\"VN\", OrderStatus.PAID, new BigDecimal(\"100\"));\n\n        assertThat(result).hasSize(1);\n        assertThat(result.get(0).getTotal()).isEqualByComparingTo(\"500.00\");\n    }\n\n    @Test\n    void searchSpecificationIgnoresAbsentFilters() {\n        Customer vn = customers.save(new Customer(\"ana@example.test\", \"Ana\", \"VN\"));\n        orders.save(order(vn, OrderStatus.NEW, \"10.00\", \"2026-10-01T00:00:00Z\"));\n        orders.save(order(vn, OrderStatus.PAID, \"20.00\", \"2026-10-02T00:00:00Z\"));\n\n        var all = orders.findAll(Specification.where(OrderSpecs.hasStatus(null)).and(OrderSpecs.totalAtLeast(null)));\n        var paid = orders.findAll(Specification.where(OrderSpecs.hasStatus(OrderStatus.PAID)));\n\n        assertThat(all).hasSize(2);\n        assertThat(paid).singleElement().extracting(Order::getStatus).isEqualTo(OrderStatus.PAID);\n    }\n\n    @Test\n    void pagingReturnsTheRightSliceAndTotal() {\n        Customer vn = customers.save(new Customer(\"ana@example.test\", \"Ana\", \"VN\"));\n        for (int i = 0; i &lt; 25; i++) {\n            orders.save(order(vn, OrderStatus.NEW, \"10.00\", \"2026-10-01T00:00:00Z\"));\n        }\n\n        Page&lt;Order&gt; page = orders.findByStatus(OrderStatus.NEW, PageRequest.of(1, 10, Sort.by(\"id\")));\n\n        assertThat(page.getContent()).hasSize(10);\n        assertThat(page.getTotalElements()).isEqualTo(25);\n        assertThat(page.getTotalPages()).isEqualTo(3);\n    }\n}</code></pre>\n<p>The first test seeds one row for each way a condition can fail, so every predicate is proven to matter: a query that forgot the status condition would return two rows. <code>flush</code> and <code>clear</code> ensure the query reads from the database and not from the persistence context. Running on PostgreSQL through Testcontainers rather than an embedded H2 catches dialect differences, particularly for native SQL and functions, as argued in why not to use H2 for tests, and the container reuse tips are in <a href=\"/library/testcontainers-service-connection-use-spring-boot\">Testcontainers with Spring Boot service connections</a>.</p>\n<h2>How Spring Data decides which query to run</h2>\n<p>Several definitions can exist for one method, and the order in which Spring Data looks for them explains behaviour that otherwise seems arbitrary. The strategy is called <code>CREATE_IF_NOT_FOUND</code> and is the default: for each repository method, Spring Data first looks for an <code>@Query</code> annotation or a <code>@NamedQuery</code> named <code>Entity.method</code>; if one exists it is used as written. Only if nothing is found does it parse the method name and derive a query. That means an <code>@Query</code> always wins over the name, which is why a method called <code>findByStatus</code> annotated with a completely different query will happily return something else, with nothing to warn you. It also means a typo in a derived method name fails at startup, while a wrong property in an <code>@Query</code> also fails at startup, since both are validated when the repository is created.</p>\n<p>Repository methods defined in a fragment take priority over both: if a custom fragment implements a method with the same signature as a method that would otherwise be derived, the fragment's implementation is used. This is how you override a single CRUD method, for example to add a default sort to <code>findAll()</code>, without touching the others.</p>\n<p>Knowing the order has a practical use. When a repository method misbehaves, ask which of the three definitions is actually in force. Enable the query lookup logging with <code>logging.level.org.springframework.data.jpa.repository.query=DEBUG</code> and the startup log lists, for each method, whether it was resolved as a declared query, a named query or a derived one. That one line is the fastest answer to \"why does this method not do what its name says\".</p>\n<h2>Optional filters inside a single JPQL query</h2>\n<p>Specifications are the clean answer to optional filters. A tempting shortcut is to write one JPQL query that ignores a parameter when it is null:</p>\n<pre><code class=\"language-java\">@Query(\"\"\"\n        select o from Order o\n        where (:status is null or o.status = :status)\n          and (:minTotal is null or o.total &gt;= :minTotal)\n        \"\"\")\nList&lt;Order&gt; search(@Param(\"status\") OrderStatus status, @Param(\"minTotal\") BigDecimal minTotal);</code></pre>\n<p>It works on small tables and has two problems. The first is plan quality: the database prepares one plan for a statement whose conditions may or may not apply, and a generic plan for <code>:status is null or o.status = :status</code> often cannot use an index on <code>status</code>, so the query is slow for exactly the selective searches. The second is a type inference failure on some databases: PostgreSQL cannot always determine the type of a bare null parameter in <code>:status is null</code> and throws <code>could not determine data type of parameter $1</code>. The usual workaround is an explicit cast, <code>cast(:status as string) is null</code>, which makes the query uglier.</p>\n<p>The rule of thumb: up to two optional filters on a small table, the shortcut is acceptable and quick to write. For a search screen on a table that matters, use specifications, which produce only the predicates that apply and so give the optimiser a plain, indexable statement every time.</p>\n<h2>Dates, enums and collections as parameters</h2>\n<p>Parameters of specific types have specific behaviours worth knowing before they bite.</p>\n<p><strong>Dates and times.</strong> Use <code>Instant</code>, <code>LocalDate</code> or <code>OffsetDateTime</code> parameters and compare half open ranges, <code>placedAt &gt;= :from and placedAt &lt; :to</code>, instead of <code>between</code>, which includes both ends and produces off by one errors when the upper bound is a date and the column is a timestamp. Pass the boundaries as instants computed in the business time zone, since <code>LocalDate</code> has no zone and the database compares in its own.</p>\n<p><strong>Enums.</strong> A parameter of the Java enum type is bound according to the mapping, <code>EnumType.STRING</code> here, so <code>:status</code> works. A literal inside JPQL must be the fully qualified enum or a string depending on the Hibernate version and mapping; passing it as a parameter avoids the question entirely.</p>\n<p><strong>Collections.</strong> <code>in :ids</code> accepts a <code>Collection</code>. An empty collection is a problem on some databases and versions, producing invalid SQL <code>in ()</code> or, in recent Hibernate, a condition that is always false; guard in code, <code>if (ids.isEmpty()) return List.of();</code>. A very large list, thousands of ids, creates a statement with thousands of parameters; PostgreSQL's limit is 32,767 bind parameters per statement, so chunk the list. For big joins against a set of ids, a temporary table or <code>= any(:array)</code> with a native query scales better.</p>\n<p><strong>Strings.</strong> Case insensitive comparison with <code>lower(x) = lower(:y)</code> cannot use a plain index; create a functional index on <code>lower(x)</code> in the database, or use a case insensitive collation, otherwise the query scans.</p>\n<h2>Transactions around repository methods</h2>\n<p>Repository methods are transactional by default, in a specific way that explains several surprises. The built in CRUD methods from <code>SimpleJpaRepository</code> are annotated <code>@Transactional</code> for writes and <code>@Transactional(readOnly = true)</code> for reads. <strong>Your own query methods are not transactional by themselves</strong>: they join an existing transaction if one is open, and otherwise run outside any, using a short lived <code>EntityManager</code> for the call. Two consequences follow.</p>\n<p>A query method that returns entities with lazy associations, called outside a transaction, returns objects whose lazy fields cannot be loaded unless Open Session in View is on. A service method annotated <code>@Transactional(readOnly = true)</code> fixes it by keeping the persistence context open for the whole method. A <code>@Modifying</code> method requires a transaction, and without one fails with <code>TransactionRequiredException</code>, so annotate the repository method or the calling service method.</p>\n<p><code>readOnly = true</code> is worth using on read paths. It tells Hibernate to skip dirty checking (it sets the flush mode to manual), which saves work, and some databases and drivers use it to route to a replica. It does not prevent writes by itself on every database, so do not depend on it as a safety mechanism.</p>\n<h2>Soft deletes, auditing and global filters</h2>\n<p>Queries interact with cross cutting entity features. A soft delete implemented with Hibernate's <code>@SQLRestriction(\"deleted = false\")</code> adds the condition to every query on the entity, derived, JPQL and Criteria, but not to native queries, which you must filter by hand; and <code>findById</code> goes through a different path (<code>em.find</code>) that does not always apply the restriction in older versions, so test the exact behaviour. The mechanics are in <a href=\"/library/hibernate-soft-delete-use-deletes\">soft deletes with Hibernate</a>. Multi tenant filters through <code>@TenantId</code> or a Hibernate filter have the same shape: they apply to entity queries and miss native SQL. Auditing columns (<code>@CreatedDate</code>) are set by entity listeners, which bulk queries bypass, so set audit columns in the update statement yourself. For each cross cutting feature your application uses, keep one test that runs a native or bulk query and asserts the filter or audit column, because that is where the feature silently stops applying.</p>\n<h2>A short performance cookbook</h2>\n<p>Most slow repository methods fall into a few categories with standard cures.</p>\n<p><strong>The missing index.</strong> Every derived query is a <code>where</code> clause; confirm that the filter and sort columns are indexed. A derived query <code>findByCountryAndActiveTrueOrderByNameAsc</code> wants a composite index on <code>(country, active, name)</code>, in that order. Add it in a migration and check the plan with <code>explain analyze</code>.</p>\n<p><strong>Counting by loading.</strong> <code>findByStatus(...).size()</code> loads every row to count them; <code>countByStatus</code> runs <code>count(*)</code>. Likewise <code>existsBy...</code> stops at the first match and is cheaper than <code>count(...) &gt; 0</code> on a big table.</p>\n<p><strong>Selecting too much.</strong> A list screen that needs three columns should project them, as in the projections post, instead of loading entities with a large text column.</p>\n<p><strong>N plus 1 from lazy associations.</strong> A query returning orders followed by a call to <code>order.getCustomer().getName()</code> for each issues one query per order. Fix it in the query: a <code>join fetch</code>, an <code>@EntityGraph</code>, a projection or batch fetching, covered in <a href=\"/library/hibernate-n-plus-1-problem-fix\">the N plus 1 problem</a>.</p>\n<p><strong>Deep offset paging.</strong> Page 5000 of a large table makes the database skip 100,000 rows each request. Switch to keyset pagination for feeds and exports.</p>\n<p><strong>Unbounded results.</strong> A method that can return the whole table is a latent outage. Accept a <code>Pageable</code>, or use <code>Top</code>/<code>limit</code>, so a caller cannot ask for everything, and set a maximum page size in the web layer (<code>spring.data.web.pageable.max-page-size</code>).</p>\n<h2>Organising query methods</h2>\n<p>A repository grows. Past a dozen query methods, the interface becomes a dumping ground. Three habits keep it manageable. Keep one repository per aggregate root, in the aggregate's package, with only the queries that aggregate's use cases need; reporting queries that span aggregates live in their own read side repository or fragment. Name methods for the business question, <code>findOverdueInvoices</code>, rather than the mechanics, even when the body is a derived query, by using <code>@Query</code> or a fragment when the derived name would be unnatural. And review queries in code review like any other code: a new <code>@Query</code> deserves a look at its SQL, its index and its test, the same attention as a new endpoint.</p>\n<h2>Worked example: building a search endpoint end to end</h2>\n<p>Put the pieces together with one feature, \"search orders\" for an admin screen, and see which tool serves each requirement. The screen has a status filter, a minimum total, a date range, a country filter, free text on the customer name, paging and a sortable header. The free text and the filters are optional, so a fixed query is out: this is a specification. The list needs the order reference, customer name, status and total only, so the result should be a projection, not the entity. The country filter reaches through a to-one association, which a specification handles with a join that does not multiply rows.</p>\n<p>The controller accepts the filter as a record bound from query parameters, with a bounded page size, and the service builds the specification and calls the repository. The sort comes from the request, which is the injection concern from the safety section, so the service passes it through an allow list. A specification returning a projection is not directly supported by <code>JpaSpecificationExecutor.findAll</code>, which returns entities, and there are two ways to deal with that. The first is to page the entities with a specification and an entity graph for the customer, then map to a record in the service inside the transaction; the cost is loading whole rows for one page of twenty, which is usually fine. The second is to write the query in a fragment with Criteria or a JPQL builder that selects the record directly, accepting more code for narrower reads.</p>\n<p>The right choice depends on the table. For a table of a few hundred thousand orders and pages of twenty, the first is adequate and much simpler to maintain, because the specifications are reused by the export and the count endpoints. For a table of hundreds of millions of rows where every millisecond of the page query counts, the second, with a covering index designed for it, is justified. State which case you are in before choosing, since over engineering the first case and under engineering the second are equally common.</p>\n<p>Two tests make the feature safe to change. A repository test seeds orders that each fail a different filter and asserts the exact result of a combined search, as in the earlier test. A web test sends <code>?sort=password,desc</code> and an oversized page size and asserts that the response is clamped and the sort falls back to the default, since those are the inputs a careless refactoring would stop handling. With the SQL log on for the first run, read the statements once: one select with the join and the filters, one count, and no query per row.</p>\n<h2>Reading query logs like a reviewer</h2>\n<p>A habit that pays back quickly is reading the generated SQL in review, not only the Java. When a pull request adds a repository method, run it once with SQL logging on and look for four things in the statement. The first is the join type: a <code>left join</code> where an <code>inner join</code> would do forces the database to keep rows it will discard, and the other way round drops rows silently when a relationship is optional. The second is the column list: a <code>select *</code> style list of every column for a feature that shows three is the cue for a projection. The third is the predicate shape: a function wrapped around an indexed column, such as <code>lower(email)</code> or a date function on <code>placed_at</code>, prevents index use unless a matching functional index exists. The fourth is the limit and offset: a missing <code>limit</code> on a method that can return many rows is a request that someone will eventually make.</p>\n<p>Add the parameter values at trace level when you need them, <code>logging.level.org.hibernate.orm.jdbc.bind=TRACE</code>, and paste the statement into a SQL console with real values to run <code>explain analyze</code>. The ten minutes spent on this for each new query are the difference between a repository that stays fast as the data grows and one that works in the demo and degrades in production. Teams that make it a checklist item in code review catch most query problems before they have data to hurt.</p>\n<h2>Return types and what they imply</h2>\n<table><thead><tr><th>Return type</th><th>Meaning</th><th>Notes</th></tr></thead><tbody><tr><td><code>T</code>, <code>Optional&lt;T&gt;</code></td><td>One result</td><td>Several rows throw <code>IncorrectResultSizeDataAccessException</code></td></tr><tr><td><code>List&lt;T&gt;</code>, <code>Collection&lt;T&gt;</code></td><td>All results</td><td>Everything in memory</td></tr><tr><td><code>Stream&lt;T&gt;</code></td><td>Lazy cursor</td><td>Needs a transaction and <code>close()</code></td></tr><tr><td><code>Page&lt;T&gt;</code></td><td>One page plus total</td><td>Runs a count query</td></tr><tr><td><code>Slice&lt;T&gt;</code></td><td>One page, knows if there is a next</td><td>No count query</td></tr><tr><td><code>Window&lt;T&gt;</code></td><td>Keyset scrolling</td><td>Spring Data 3.1 and later, cursor based</td></tr><tr><td><code>long</code>, <code>boolean</code></td><td>Count or existence</td><td><code>count...By</code>, <code>exists...By</code></td></tr><tr><td><code>CompletableFuture&lt;T&gt;</code> with <code>@Async</code></td><td>Asynchronous</td><td>Runs on another thread; mind transactions</td></tr></tbody></table>\n<p><code>Window&lt;T&gt;</code> with <code>ScrollPosition</code> is Spring Data's built in keyset paging, <code>findFirst10ByStatusOrderById(status, ScrollPosition.keyset())</code>, worth knowing for deep result sets.</p>\n<h2>Common mistakes</h2>\n<p><strong>A derived query where the name should have been a query.</strong> If you cannot read the method name aloud without losing track, write <code>@Query</code>.</p>\n<p><strong>Loading entities for a read only list.</strong> Project to a record or interface and skip dirty checking and lazy proxies.</p>\n<p>**<code>Page</code> for everything.** The count query doubles the cost of large tables; use <code>Slice</code> or keyset pagination for feeds.</p>\n<p><strong>Fetch join plus paging.</strong> The in-memory pagination warning; use the two step approach.</p>\n<p><strong>Native queries for convenience.</strong> Native SQL for a query JPQL could have expressed ties you to one database for no gain.</p>\n<p>**Forgetting that <code>@Query</code> strings are not refactored.** A property rename updates derived methods only through the startup check; keep tests so a rename fails loudly.</p>\n<p><strong>Open Session in View hiding lazy loads.</strong> A query that returns entities whose lazy associations are touched later multiplies statements; see <a href=\"/library/spring-open-view-mvc-session-explained\">open session in view</a>.</p>\n<h2>A decision path</h2>\n<p>Ask in order. Is it one or two conditions on one entity? A derived query. Is it a fixed query with joins or aggregates? <code>@Query</code> JPQL, with a projection when you need fewer columns. Does it need database features or hand tuned SQL? A native <code>@Query</code>, with a test. Are the filters optional and driven by user input? A <code>Specification</code>. Does it need an <code>EntityManager</code>, Criteria building, batching or another library? A custom fragment. Is it a large export? Stream it, or move to a stateless session. At each step, check the SQL, then test it on the real engine.</p>\n<h2>One more habit: keep queries near their tests</h2>\n<p>When a repository method lives beside a test that seeds the rows it must and must not return, a later change to the query has a safety net. Keep the test class in the same package as the repository, name tests after the business rule they protect, and let the seed data show the edge cases the query handles. A future maintainer who wonders why a condition exists can read the test that fails without it.</p>\n<h2>When this does not apply</h2>\n<p>If the application's queries are mostly reporting, aggregates over many tables with grouping and window functions, a SQL oriented layer such as jOOQ or <code>JdbcClient</code> is a better fit than JPQL, as discussed in <a href=\"/library/orm-vs-jdbc-reporting-hibernate-spring\">Hibernate, JDBC and jOOQ for reporting</a>. If you use Spring Data JDBC or R2DBC instead of JPA, the derived query and <code>@Query</code> mechanics are similar but the entity model differs and several features here, specifications and entity graphs, do not exist. The primary sources are the <a href=\"https://docs.spring.io/spring-data/jpa/reference/jpa/query-methods.html\">Spring Data JPA reference on query methods</a>, the <a href=\"https://docs.spring.io/spring-data/jpa/reference/jpa/specifications.html\">Specifications chapter</a> and the <a href=\"https://docs.jboss.org/hibernate/orm/7.0/querylanguage/html_single/Hibernate_Query_Language.html\">Hibernate query language guide</a>.</p>","date_published":"2026-11-14T04:13:31+00:00","tags":["Spring Boot"]},{"id":"https://javahacks.dev/library/unsupportedoperationexception-fix-immutable-lists","url":"https://javahacks.dev/library/unsupportedoperationexception-fix-immutable-lists","title":"Fix UnsupportedOperationException on Immutable Lists","summary":"Why List.of, Arrays.asList and Stream.toList reject changes with UnsupportedOperationException, and how to get a list you can modify.","content_html":"<p>You called <code>add</code> on a list and got an exception with no message:</p>\n<pre><code class=\"language-java\">List&lt;String&gt; tags = List.of(\"java\", \"spring\");\ntags.add(\"hibernate\");</code></pre>\n<pre><code class=\"language-text\">Exception in thread \"main\" java.lang.UnsupportedOperationException\n\tat java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)</code></pre>\n<p>The list was immutable on purpose. The exception is the contract, and the stack trace even names <code>ImmutableCollections</code>. The question is which factory gave you the list and what to do instead. The language-level view is in <a href=\"/library/modern-java-guide-language\">the modern Java guide</a>.</p>\n<h2>Which methods return which kind of list</h2>\n<table><thead><tr><th>Source</th><th><code>add</code> / <code>remove</code></th><th><code>set</code></th><th>Notes</th></tr></thead><tbody><tr><td><code>List.of(...)</code></td><td>throws</td><td>throws</td><td>Immutable, rejects <code>null</code> elements</td></tr><tr><td><code>Stream.toList()</code></td><td>throws</td><td>throws</td><td>Immutable, allows <code>null</code></td></tr><tr><td><code>Collectors.toList()</code></td><td>works in practice</td><td>works</td><td>No guarantee in the specification</td></tr><tr><td><code>Arrays.asList(array)</code></td><td>throws</td><td>works</td><td>Fixed-size view backed by the array</td></tr><tr><td><code>Collections.unmodifiableList(l)</code></td><td>throws</td><td>throws</td><td>Read-only view of another list</td></tr><tr><td><code>new ArrayList&lt;&gt;(...)</code></td><td>works</td><td>works</td><td>An ordinary modifiable list</td></tr></tbody></table>\n<p><code>Collectors.toList()</code> returns an <code>ArrayList</code> today, and the documentation promises nothing, so code that relies on that is fragile. If a method returns <code>Collectors.toList()</code> in one version of a library and <code>Stream.toList()</code> in the next, callers that mutate the result start throwing.</p>\n<h2>Fix: make a copy you own</h2>\n<pre><code class=\"language-java\">List&lt;String&gt; tags = new ArrayList&lt;&gt;(List.of(\"java\", \"spring\"));\ntags.add(\"hibernate\");</code></pre>\n<p>The copy constructor takes the elements and gives you a mutable list. This is also how to defend against a caller who passes you an immutable list you need to change, and how to hand out data without letting others change your internal list: return <code>List.copyOf(internal)</code>.</p>\n<h2>Arrays.asList is a special case</h2>\n<pre><code class=\"language-java\">List&lt;String&gt; days = Arrays.asList(\"mon\", \"tue\");\ndays.set(0, \"sun\");         // works, and writes through to the array\ndays.add(\"wed\");            // UnsupportedOperationException</code></pre>\n<p>The list is a window onto the array, and an array cannot grow. Wrap it with <code>new ArrayList&lt;&gt;(Arrays.asList(...))</code> if you want to add, or use <code>List.of</code> if you want it fixed.</p>\n<h2>The view trap</h2>\n<pre><code class=\"language-java\">List&lt;String&gt; source = new ArrayList&lt;&gt;(List.of(\"a\", \"b\"));\nList&lt;String&gt; readOnly = Collections.unmodifiableList(source);\nsource.add(\"c\");\nSystem.out.println(readOnly);       // [a, b, c]</code></pre>\n<p><code>unmodifiableList</code> blocks changes through the wrapper, not through the original. If you want a snapshot nobody can change, use <code>List.copyOf(source)</code>.</p>\n<h2>The same rules for sets and maps</h2>\n<p><code>Set.of</code>, <code>Map.of</code>, <code>Map.ofEntries</code> and <code>Map.copyOf</code> are immutable. They also reject duplicate elements or keys at creation with <code>IllegalArgumentException</code>, and reject <code>null</code>. If a <code>Map.of</code> call throws <code>NullPointerException</code>, a value or key was <code>null</code>.</p>\n<h2>In frameworks</h2>\n<p>A Spring <code>@ConfigurationProperties</code> list or a JPA collection may be unmodifiable or a Hibernate wrapper that throws on certain operations. A repository method that returns <code>List</code> from a <code>Stream.toList()</code> is immutable. If the exception appears after you changed a collection type or upgraded a library, check the source of the list.</p>\n<h2>Which factory gives which behaviour</h2>\n<p>The exception message is <code>null</code> in every case, so it never says which list you hold. This program tries to modify lists from the common factories and prints what happens. It ran on Eclipse Temurin 25.0.5.</p>\n<pre data-filename=\"Immut.java\"><code class=\"language-java\">tryAdd(\"List.of\", List.of(\"a\", \"b\"));\ntryAdd(\"Arrays.asList\", Arrays.asList(\"a\", \"b\"));\ntryAdd(\"stream.toList()\", Stream.of(\"a\", \"b\").toList());\ntryAdd(\"Collectors.toList\", Stream.of(\"a\", \"b\").collect(Collectors.toList()));\ntryAdd(\"Collections.unmodifiableList\", Collections.unmodifiableList(new ArrayList&lt;&gt;(List.of(\"a\"))));</code></pre>\n<pre><code class=\"language-text\">List.of: UnsupportedOperationException message=null\nArrays.asList: UnsupportedOperationException message=null\nstream.toList(): UnsupportedOperationException message=null\nCollectors.toList: added, size 3\nCollections.unmodifiableList: UnsupportedOperationException message=null</code></pre>\n<p>Only <code>Collectors.toList()</code> returned a list you may add to, and even that is only an implementation detail the documentation does not promise. <code>Stream.toList()</code>, added in JDK 16, returns an unmodifiable list, and code that replaced <code>collect(Collectors.toList())</code> with it during a modernisation is a typical source of this exception months later. If a caller will modify the result, say so in the method contract and return a new <code>ArrayList</code>.</p>\n<h2>Modifying vs replacing in <code>Arrays.asList</code></h2>\n<p><code>Arrays.asList</code> is the odd one. It is fixed-size but writable: you can replace elements, and the changes write through to the array, yet you cannot add or remove.</p>\n<pre><code class=\"language-text\">Arrays.asList: set ok -&gt; [z, b]\nList.of.set: UnsupportedOperationException</code></pre>\n<p>That is why the same call sequence can pass a test with one factory and fail with another. A method that sorts its input in place works on <code>Arrays.asList</code> (it only sets elements) and fails on <code>List.of</code>. The error is in the method that mutates a list it was handed.</p>\n<h2>Unmodifiable is not the same as immutable</h2>\n<p><code>Collections.unmodifiableList</code> returns a read-only view of another list. Changes to the original appear in the view, which defeats a defensive copy. <code>List.copyOf</code> takes a snapshot.</p>\n<pre><code class=\"language-text\">view reflects the source: [a, b, c]\nList.copyOf is a snapshot : [a, b, c]</code></pre>\n<p>The view showed <code>c</code> after the original gained it. The copy was taken after <code>c</code> and before <code>d</code>, and stayed at <code>[a, b, c]</code> when <code>d</code> was added later. For a class that exposes a collection from its state, return <code>List.copyOf(items)</code> or an unmodifiable view, and decide which on purpose: the copy is safe against later changes and costs a copy on each call, the view is free and moves with the source. Also remember that <code>List.of</code> rejects null elements with a <code>NullPointerException</code>, which is the other surprise the run confirmed.</p>\n<h2>Fix it where the mutation happens</h2>\n<p>Three fixes cover almost every case, in order of preference. Change the code that mutates to work on a copy it owns, so the contract of the method does not depend on what its caller passes.</p>\n<pre><code class=\"language-java\">public List&lt;String&gt; sortedNames(List&lt;String&gt; input) {\n    List&lt;String&gt; copy = new ArrayList&lt;&gt;(input);      // a list we own\n    Collections.sort(copy);\n    return copy;\n}</code></pre>\n<p>Or use a method that does not mutate: <code>input.stream().sorted().toList()</code>. Or, when the caller really owns the list and the method is meant to mutate it, document that and make the caller pass an <code>ArrayList</code>. Resist catching <code>UnsupportedOperationException</code> to fall back to a copy, which hides the contract problem and makes behaviour depend on the argument type.</p>\n<h2>In frameworks</h2>\n<p>Spring, Hibernate and Jackson all return unmodifiable collections in places. Spring's <code>Environment</code> and request parameter maps are read-only. Hibernate hands back its own <code>PersistentBag</code>, which is modifiable, but <code>List.of</code> assigned to an entity's collection field can break Hibernate's change tracking, so initialise entity collections with <code>new ArrayList&lt;&gt;()</code>. Jackson deserialises into <code>ArrayList</code> by default and into an immutable list only for types you declare as such. When the stack trace shows the exception thrown from inside a library, read upward to the first frame of your code: that is the method holding the wrong list.</p>\n<h2>Stop copying between collections by accident</h2>\n<p>Defensive copies fix mutation bugs and cost allocation, so make them on boundaries, not everywhere. Copy when a mutable list enters your class from outside and you will hold it, and copy when a mutable field leaves it. Inside a class, pass collections by reference and treat them as read-only by convention. A record with a list component is a good example of where to copy once:</p>\n<pre><code class=\"language-java\">record Order(String id, List&lt;String&gt; lines) {\n    Order {\n        lines = List.copyOf(lines);        // snapshot at construction; also rejects null elements\n    }\n}</code></pre>\n<p>The compact constructor makes the record deeply immutable with respect to its list. Callers that pass an <code>ArrayList</code> and keep modifying it do not affect the order, and callers that try <code>order.lines().add(\"x\")</code> get the exception this post is about, at the point of the mistake and with a stack trace that names their line, not a library's.</p>\n<h2>Where this does not apply</h2>\n<p>If you wanted to modify a list while looping over it and got <code>ConcurrentModificationException</code>, the list is mutable and the loop is wrong: see <a href=\"/library/concurrentmodificationexception-fix-java-collections\">that fix</a>. Prefer immutable collections for data that crosses a method boundary: they cannot be corrupted by a caller. Another runtime exception that follows from wrong assumptions about collections is <a href=\"/library/classcastexception-fix-heap-pollution-java\">ClassCastException from heap pollution</a>. The [<code>List</code> interface documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html) lists the immutable factories, and <a href=\"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/doc-files/coll-overview.html\">the Collections Framework overview</a> explains the unmodifiable wrappers.</p>","date_published":"2026-11-14T04:12:31+00:00","tags":["Java Core"]},{"id":"https://javahacks.dev/library/java-threads-tutorial-explained-thread-executorservice","url":"https://javahacks.dev/library/java-threads-tutorial-explained-thread-executorservice","title":"Java Threads Explained From Thread to ExecutorService","summary":"Learn how to start threads, wait for them, share results with futures and move to executors and virtual threads, with the rules that keep code correct.","content_html":"<p>Concurrency in Java begins with one class and ends with a toolbox. This post starts at the beginning, a single thread, and climbs to executors and virtual threads, with the rule that matters at each step. The examples run on Java 25. The later steps are in <a href=\"/library/java-memory-model-happens-before-explained\">the memory model</a> and <a href=\"/library/java-volatile-vs-synchronized-atomic\">volatile vs synchronized vs atomic</a>.</p>\n<h2>A thread runs a task</h2>\n<pre><code class=\"language-java\">Thread t = new Thread(() -&gt; System.out.println(\"running in \" + Thread.currentThread().getName()));\nt.start();\nt.join();</code></pre>\n<p>The lambda is a <code>Runnable</code>. <code>start()</code> asks the JVM to create an operating system thread and call <code>run()</code> on it. Calling <code>t.run()</code> directly would just run it in the current thread, which is a common mistake. <code>join()</code> blocks the current thread until <code>t</code> finishes. The thread name is <code>Thread-0</code> by default; give it a meaningful one with <code>new Thread(task, \"importer\")</code>, because names appear in thread dumps.</p>\n<p>An uncaught exception in a thread kills that thread only and prints a stack trace to the standard error; the rest of the program continues. Set an <code>UncaughtExceptionHandler</code> or catch inside the task.</p>\n<h2>Why a pool</h2>\n<p>Creating a thread costs time and memory (a stack of about a megabyte of address space by default), and starting a thousand of them is a bad idea. An <code>ExecutorService</code> keeps a pool of threads and feeds them tasks:</p>\n<pre><code class=\"language-java\">ExecutorService pool = Executors.newFixedThreadPool(4);\n\nFuture&lt;Integer&gt; answer = pool.submit(() -&gt; 6 * 7);\nSystem.out.println(answer.get());       // prints 42\n\npool.shutdown();</code></pre>\n<p><code>submit</code> takes a <code>Callable</code> (which returns a value and may throw) and returns a <code>Future</code>. <code>get()</code> waits for the result and rethrows task failures as <code>ExecutionException</code>. Always shut the executor down: a non-daemon pool thread keeps the JVM alive after <code>main</code> ends. Since Java 19 an <code>ExecutorService</code> is <code>AutoCloseable</code>, so try-with-resources shuts it down and waits.</p>\n<h2>Running several tasks</h2>\n<pre><code class=\"language-java\">try (var pool = Executors.newFixedThreadPool(3)) {\n    List&lt;Callable&lt;String&gt;&gt; jobs = List.of(() -&gt; \"a\", () -&gt; \"b\", () -&gt; \"c\");\n    List&lt;Future&lt;String&gt;&gt; results = pool.invokeAll(jobs);\n    for (Future&lt;String&gt; f : results) {\n        System.out.println(f.get());\n    }\n}</code></pre>\n<p><code>invokeAll</code> runs every job and returns the futures in the order of the list, so this prints <code>a</code>, <code>b</code>, <code>c</code> in that order even though the jobs run in parallel. Output from the tasks themselves would interleave unpredictably.</p>\n<h2>Composing with CompletableFuture</h2>\n<pre><code class=\"language-java\">CompletableFuture&lt;String&gt; greeting = CompletableFuture\n        .supplyAsync(() -&gt; \"hello\")\n        .thenApply(String::toUpperCase)\n        .thenCombine(CompletableFuture.supplyAsync(() -&gt; \"world\"), (a, b) -&gt; a + \" \" + b);\n\nSystem.out.println(greeting.join());     // HELLO world</code></pre>\n<p><code>supplyAsync</code> runs on the common pool unless you pass an executor. For blocking calls, pass your own executor, so you do not starve the shared pool.</p>\n<h2>The rule under everything</h2>\n<p>Threads run at the same time and share memory. Two threads incrementing a plain <code>int</code> lose updates, and a value written by one may never be seen by another. The fixes are locks (<code>synchronized</code>), <code>volatile</code> for visibility and atomics for counters. Which tool for which problem is in <a href=\"/library/java-volatile-vs-synchronized-atomic\">volatile vs synchronized vs atomic</a>, and the formal guarantees in <a href=\"/library/java-memory-model-happens-before-explained\">the memory model</a>. The simplest safe design shares nothing mutable: pass immutable messages.</p>\n<h2>Virtual threads</h2>\n<p>Java 21 finalized virtual threads (<a href=\"https://openjdk.org/jeps/444\">JEP 444</a>). A virtual thread is cheap, so you create one per task:</p>\n<pre><code class=\"language-java\">try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {\n    for (int i = 0; i &lt; 10_000; i++) {\n        executor.submit(() -&gt; fetch());\n    }\n}</code></pre>\n<p>They shine when tasks mostly wait for I/O. For heavy computation, use a fixed pool near the core count, because more threads than cores only add switching.</p>\n<h2>Shut a pool down properly</h2>\n<p>A pool created with <code>Executors.newFixedThreadPool</code> keeps its threads alive, and the JVM does not exit while they exist. A pool that is never shut down is a leak in a test suite and a hang in a command-line tool. The pattern has two steps, a polite request and a forced stop after a deadline:</p>\n<pre><code class=\"language-java\">void shutdown(ExecutorService pool) {\n    pool.shutdown();                                  // no new tasks, finish queued ones\n    try {\n        if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {\n            pool.shutdownNow();                       // interrupt running tasks\n            if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {\n                System.err.println(\"Pool did not terminate\");\n            }\n        }\n    } catch (InterruptedException e) {\n        pool.shutdownNow();\n        Thread.currentThread().interrupt();\n    }\n}</code></pre>\n<p>Since Java 19, <code>ExecutorService</code> is <code>AutoCloseable</code>, and <code>close()</code> does the polite part and waits, so a try-with-resources block replaces most of the above for short-lived pools. Tasks must respond to interruption for <code>shutdownNow</code> to work: a loop that never checks <code>Thread.currentThread().isInterrupted()</code> and never calls a blocking method keeps running.</p>\n<h2>Exceptions vanish inside submit</h2>\n<p>An exception thrown in a task passed to <code>execute</code> goes to the thread's uncaught exception handler and prints a stack trace. An exception in a task passed to <code>submit</code> is stored in the returned <code>Future</code>, and nothing is printed until someone calls <code>get</code>:</p>\n<pre><code class=\"language-java\">Future&lt;?&gt; f = pool.submit(() -&gt; {\n    throw new IllegalStateException(\"boom\");\n});\n// nothing happens here, the failure is silent\nf.get();    // throws ExecutionException wrapping the IllegalStateException</code></pre>\n<p>A fire-and-forget <code>submit</code> that fails is the commonest way to lose an error in concurrent code. Either keep the future and check it, or catch and log inside the task. A wrapper that logs every failure belongs in one helper used by all background work.</p>\n<h2>Sizing a pool from the work</h2>\n<p>The right size depends on what the tasks do while they run:</p>\n<table><thead><tr><th>Kind of task</th><th>Pool size</th><th>Reason</th></tr></thead><tbody><tr><td>CPU-bound, no waiting</td><td>Number of cores, or one more</td><td>More threads only add switching</td></tr><tr><td>I/O-bound, mostly waiting</td><td>Cores times (1 plus wait time over compute time)</td><td>Threads spend time blocked, so more can run</td></tr><tr><td>Mixed</td><td>Separate pools for each kind</td><td>One slow call must not starve the computation</td></tr><tr><td>Unbounded, short tasks</td><td>Virtual threads</td><td>No pool size to tune</td></tr></tbody></table>\n<p>A task that waits 90 ms on a database for each 10 ms of computation has a ratio of 9, so a pool for 8 cores is about 80 threads, and it cannot exceed the number of database connections available. The formula gives a start, and a load test finds the real number.</p>\n<h2>Name your threads</h2>\n<p>A thread dump full of <code>pool-3-thread-7</code> says nothing about who owns it. A <code>ThreadFactory</code> gives threads a name that points to the code:</p>\n<pre><code class=\"language-java\">ThreadFactory factory = Thread.ofPlatform().name(\"invoice-worker-\", 0).daemon(false).factory();\nExecutorService pool = Executors.newFixedThreadPool(4, factory);</code></pre>\n<p><code>Thread.ofPlatform().name(prefix, start)</code> numbers the threads <code>invoice-worker-0</code> and so on. When a dump later shows eight threads stuck in the same method, the prefix tells which component to look in. Naming costs one line and saves an hour in production.</p>\n<h2>Waiting for several results</h2>\n<p><code>invokeAll</code> runs a list of tasks and returns when all are done, and <code>invokeAny</code> returns the first successful result and cancels the others:</p>\n<pre><code class=\"language-java\">List&lt;Callable&lt;Price&gt;&gt; quotes = List.of(() -&gt; vendorA.quote(item), () -&gt; vendorB.quote(item));\nPrice cheapest = pool.invokeAny(quotes);</code></pre>\n<p><code>invokeAny</code> suits a request to redundant providers where any answer is good. If every task fails, it throws an <code>ExecutionException</code> with the last failure. Give both a timeout overload, so one hung vendor does not hold the caller forever.</p>\n<h2>Reading a thread dump for the first time</h2>\n<p>A thread dump is the best way to learn how threads behave in a real program. Start a small server, take a dump with <code>jcmd &lt;pid&gt; Thread.print</code>, and read the states: <code>RUNNABLE</code> for running or ready, <code>BLOCKED</code> for waiting on a monitor, <code>WAITING</code> and <code>TIMED_WAITING</code> for parked or sleeping. Find your pool's thread names, and compare the stacks of idle and busy workers.</p>\n<p>Doing it once on a harmless program makes the dump familiar, so that on the day of an incident the output looks routine and not frightening.</p>\n<h2>Where threads are the wrong abstraction</h2>\n<p>Many tasks are better as a parallel stream (<code>list.parallelStream()</code>) when the work is a pure computation over a collection, or as a message queue between components. For deadlocks and rejected tasks, see <a href=\"/library/java-deadlock-thread-dump-fix-deadlocks\">deadlocks</a> and <a href=\"/library/rejectedexecutionexception-fix-full-thread-pool\">RejectedExecutionException</a>. The <a href=\"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/package-summary.html\">java.util.concurrent documentation</a> is the reference.</p>","date_published":"2026-11-14T04:11:31+00:00","tags":["Concurrency"]},{"id":"https://javahacks.dev/library/jvm-works-bytecode-machine-code","url":"https://javahacks.dev/library/jvm-works-bytecode-machine-code","title":"How the JVM Works From Bytecode to Machine Code Step by Step","summary":"Follow Java code from source to bytecode, class loading, interpretation and JIT compilation, and see why the JVM is slow at first and fast later.","content_html":"<p>A Java program is not run by the processor. It is run by another program, the Java Virtual Machine, which reads a compact instruction format called bytecode and decides, at run time and method by method, whether to interpret it or turn it into native machine code. That one design choice explains most of what surprises people about Java: the same jar runs on a laptop and a server, the first request is slower than the thousandth, the memory footprint is larger than the heap you configured, and a benchmark that looks fast in <code>main</code> is not.</p>\n<p>This post follows a four-line program through the whole pipeline with real tool output: source to bytecode, class loading and linking, interpretation, then compilation. Commands ran on JDK 17.0.1; the pipeline is the same in Java 25.</p>\n<h2>Source to bytecode</h2>\n<p>Start with a program small enough to read its bytecode in full:</p>\n<pre data-filename=\"src/main/java/dev/javahacks/jvm/Add.java\"><code class=\"language-java\">public class Add {\n    static int add(int a, int b) {\n        return a + b;\n    }\n\n    public static void main(String[] args) {\n        int total = 0;\n        for (int i = 0; i &lt; 3; i++) {\n            total = add(total, i);\n        }\n        System.out.println(total);\n    }\n}</code></pre>\n<p><code>javac Add.java</code> writes <code>Add.class</code>. The <code>javap</code> tool disassembles it:</p>\n<pre><code class=\"language-bash\">javac Add.java\njavap -c -p Add</code></pre>\n<pre><code class=\"language-text\">  static int add(int, int);\n    Code:\n       0: iload_0\n       1: iload_1\n       2: iadd\n       3: ireturn\n\n  public static void main(java.lang.String[]);\n    Code:\n       0: iconst_0\n       1: istore_1\n       2: iconst_0\n       3: istore_2\n       4: iload_2\n       5: iconst_3\n       6: if_icmpge     21\n       9: iload_1\n      10: iload_2\n      11: invokestatic  #7                  // Method add:(II)I\n      14: istore_1\n      15: iinc          2, 1\n      18: goto          4\n      21: getstatic     #13                 // Field java/lang/System.out:Ljava/io/PrintStream;\n      24: iload_1\n      25: invokevirtual #19                 // Method java/io/PrintStream.println:(I)V\n      28: return</code></pre>\n<p>Read <code>add</code> first. The JVM is a stack machine: <code>iload_0</code> and <code>iload_1</code> push the two arguments onto an operand stack, <code>iadd</code> pops both and pushes the sum, <code>ireturn</code> returns the top. There are no registers in the instruction set, which is what keeps bytecode independent of any processor. The <code>main</code> method shows a loop as plain jumps: <code>if_icmpge 21</code> leaves the loop when <code>i &gt;= 3</code>, <code>goto 4</code> goes back. The <code>#7</code> and <code>#13</code> are indexes into the constant pool, the table of names and literals every class file carries.</p>\n<p>The class file starts with a header the JVM checks before anything else. <code>javap -v Add</code> shows <code>major version: 61</code>, which is Java 17. A class compiled for a newer version than the running JVM is refused with the error in <a href=\"/library/unsupportedclassversionerror-fix-class-file-version-mismatch\">UnsupportedClassVersionError</a>.</p>\n<h2>Loading, linking and initialization</h2>\n<p>The JVM does not read every class at startup. A class is loaded the first time something needs it, in three phases:</p>\n<ol><li><strong>Loading.</strong> A class loader finds the bytes (from the JDK's own image, a jar or a directory) and builds the in-memory representation in metaspace. The loaders form a parent-first chain: the application loader asks the platform loader, which asks the boot loader, and only if all refuse does the application loader look in your classpath. That order is why you cannot replace <code>java.lang.String</code> by putting your own on the classpath.</li><li><strong>Linking.</strong> The bytecode verifier checks that the class is well-formed: stack depths match, types are consistent, jumps land on instruction boundaries. Then static fields get default values, and symbolic references are resolved lazily.</li><li><strong>Initialization.</strong> Static initializers and static field assignments run, once, before the first use of the class.</li></ol>\n<p>You can see this laziness. Run the program with class-load logging and count the lines that mention your class:</p>\n<pre><code class=\"language-bash\">java -Xlog:class+load -cp . Add | grep -c \"Add \"\njava -Xlog:class+load -cp . Add | wc -l</code></pre>\n<pre><code class=\"language-text\">1\n405</code></pre>\n<p>The program loaded 405 classes to print a single number, almost all of them JDK classes from the shared archive, and <code>Add</code> exactly once. When a class is missing at the moment of first use, you get the exceptions explained in <a href=\"/library/classnotfoundexception-fix-noclassdeffounderror\">ClassNotFoundException and NoClassDefFoundError</a>, and the memory those 753 classes occupy is the topic of <a href=\"/library/jvm-memory-areas-heap-stack-metaspace\">JVM memory areas</a>.</p>\n<h2>Interpreting first, then compiling</h2>\n<p>The interpreter executes the bytecode directly, one instruction at a time. It starts instantly and runs slowly. While it runs, the JVM counts how many times each method is called and how many times each loop jumps backward. When a count crosses a threshold, the method is queued for compilation to machine code, which happens on background compiler threads while the program keeps running.</p>\n<p>The difference is not subtle. A tiny method called twenty million times per round, timed on a 10-core laptop:</p>\n<pre><code class=\"language-text\">interpreter only (-Xint):          467 ms per round\ndefault (interpreter, C1, C2):      13 ms per round after warm-up</code></pre>\n<p>That is a factor of 35 from compilation alone. There are two compilers. C1 compiles quickly with modest optimization and inserts profiling counters. C2 takes its time and uses the recorded profile, which types reached which call, which branches were taken, to inline aggressively, remove checks that were never needed and keep objects out of the heap entirely. The step-by-step account of the tiers, with <code>-XX:+PrintCompilation</code> output, is in <a href=\"/library/java-jit-tiered-compilation-c1-c2\">tiered compilation with C1 and C2</a>.</p>\n<p>Compiled code is a bet on the profile. If the bet fails, a new subclass is loaded or a rare branch fires, the JVM throws the compiled code away and goes back to the interpreter, then recompiles with the new facts. This is called deoptimization, and it is why Java can optimize more aggressively than an ahead-of-time compiler, which has to be right without seeing the program run.</p>\n<h2>Garbage collection runs alongside</h2>\n<p>While methods run, the heap fills with objects. The garbage collector reclaims whatever is no longer reachable from a root (a stack variable, a static field, a live thread). The program never frees anything. Which collector runs, and what pauses it causes, depends on the collector you choose: <a href=\"/library/java-garbage-collection-explained-generations-up\">generations, regions and pauses</a> and <a href=\"/library/g1-vs-zgc-vs-shenandoah-parallel\">G1 against ZGC and Shenandoah</a> cover that choice. For this post, the relevant fact is that collection and compilation both compete with your threads for CPU, and the JVM starts several of each.</p>\n<h2>See the whole pipeline in one run</h2>\n<p>Combine the previous tools on one process and you can watch each stage in a log:</p>\n<pre><code class=\"language-bash\">java -Xlog:class+load:file=load.log \\\n     -Xlog:gc:file=gc.log \\\n     -XX:+PrintCompilation \\\n     -cp . Add</code></pre>\n<p><code>load.log</code> fills first and quickly. <code>PrintCompilation</code> stays empty for a program this short, because nothing runs often enough to reach a threshold: the whole life of <code>Add</code> happens in the interpreter. That is the point of the next section.</p>\n<h2>What warm-up means in practice</h2>\n<p>The pipeline has a cost curve. In the first seconds of a process most code is interpreted, classes are still loading and the compilers are busy, so throughput is low and latency is high. Then the hot methods compile and the curve flattens. Consequences you will meet:</p>\n<ul><li><strong>Benchmarks.</strong> A microbenchmark must warm up, then measure. A loop in <code>main</code> that times itself measures the interpreter, C1, the compile pauses and sometimes nothing at all, when C2 deletes work whose result is unused. <a href=\"https://github.com/openjdk/jmh\">JMH</a> exists to handle this.</li><li><strong>Deployments.</strong> A service sent full traffic the moment it starts shows slow requests for the first minute. Send warm-up traffic before the load balancer does, or ramp up gradually.</li><li><strong>Short-lived processes.</strong> A command-line tool or a function that runs for two seconds lives entirely in the slow phase. Class Data Sharing, native images and the ahead-of-time cache work in JDK 24 and later move work from run time to build time. See <a href=\"/library/quarkus-starts-fast\">why Quarkus starts fast</a>.</li><li><strong>Memory.</strong> The JVM's footprint is more than the heap: metaspace, the code cache for compiled methods, thread stacks and direct buffers all count.</li></ul>\n<h2>Where this model stops</h2>\n<p>This account describes HotSpot, the JVM in OpenJDK and most distributions. Other runtimes differ: GraalVM's native image compiles ahead of time with no JIT, and Android does not run JVM bytecode at all. Language features also evolve the model, which is why the language and the platform are covered side by side in <a href=\"/library/modern-java-guide-language\">the modern Java guide</a>. The authoritative reading is the <a href=\"https://docs.oracle.com/javase/specs/jvms/se25/html/index.html\">Java Virtual Machine Specification</a> and the <a href=\"https://docs.oracle.com/en/java/javase/25/vm/\">HotSpot documentation</a>.</p>","date_published":"2026-11-14T04:10:31+00:00","tags":["JVM & Performance"]},{"id":"https://javahacks.dev/library/clean-code-java-rules-hold-up","url":"https://javahacks.dev/library/clean-code-java-rules-hold-up","title":"Clean Code in Java Rules That Hold Up in Real Codebases","summary":"A short list of clean code rules for Java that survive contact with real projects: naming, small methods, immutability, exceptions and when to ignore a rule.","content_html":"<p>Clean code advice has a bad reputation because it is often given as commandments. The rules below come from what makes a Java codebase easier to change, and each one comes with the case where it stops helping. They apply to Java 25 style code, with records and sealed types where relevant, which are covered in <a href=\"/library/modern-java-guide-language\">the modern Java guide</a>.</p>\n<h2>1. Name for meaning</h2>\n<pre><code class=\"language-java\">// before\nList&lt;Order&gt; l = repo.f(c, 30);\n\n// after\nList&lt;Order&gt; recentOrders = orders.findByCustomerSince(customer, Duration.ofDays(30));</code></pre>\n<p>A name is documentation that cannot go stale. Use nouns for values, verbs for actions and the domain's own words. Avoid abbreviations except those everyone knows (<code>id</code>, <code>url</code>). A long name is fine; a name that needs a comment is not. Rename freely: the IDE does it safely.</p>\n<h2>2. Keep methods at one level of abstraction</h2>\n<p>A method that parses input, validates it, applies pricing and writes to the database mixes levels. Split by what, not by length:</p>\n<pre><code class=\"language-java\">Order place(CreateOrder request) {\n    validate(request);\n    Order order = pricing.priceOf(request);\n    return orders.save(order);\n}</code></pre>\n<p>The top method reads as a story, and each helper holds the detail. There is no magic line count; 15 to 20 lines is a hint that a method does several things, and a 40-line method that is a clear <code>switch</code> over cases may be fine.</p>\n<h2>3. Prefer immutable data</h2>\n<pre><code class=\"language-java\">public record Money(long cents, String currency) {\n    public Money {\n        Objects.requireNonNull(currency);\n        if (cents &lt; 0) throw new IllegalArgumentException(\"cents must not be negative\");\n    }\n}</code></pre>\n<p>An object that cannot change cannot be changed by surprise, can be shared across threads and is safe as a map key. Use records for values, <code>final</code> fields elsewhere and <code>List.copyOf</code> at boundaries. The cost is allocation for each change, which is usually irrelevant. A JPA entity is the common exception, since the framework needs mutable state.</p>\n<h2>4. Fail fast and clearly</h2>\n<p>Check arguments where they enter and throw an exception that names the problem:</p>\n<pre><code class=\"language-java\">if (quantity &lt;= 0) {\n    throw new IllegalArgumentException(\"quantity must be positive but was \" + quantity);\n}</code></pre>\n<p>A <code>null</code> or a negative number that travels three layers before blowing up is expensive to debug. Do not catch <code>Exception</code> to hide a failure, and do not return <code>null</code> to mean \"error\". Use exceptions for exceptional cases and <code>Optional</code> or an empty collection for absence. Reading the failures later is the subject of <a href=\"/library/read-java-stack-trace-correctly\">how to read a stack trace</a>.</p>\n<h2>5. Avoid boolean parameters</h2>\n<p><code>render(order, true, false)</code> tells the reader nothing. Replace flags with two methods, an enum or a parameter object:</p>\n<pre><code class=\"language-java\">render(order, Format.PDF, Language.FRENCH);</code></pre>\n<p>Each flag doubles the paths through a method, and tests must cover them all.</p>\n<h2>6. Comments explain why</h2>\n<p>A comment that restates the code (<code>// increment i</code>) is noise that rots. Write comments for decisions that the code cannot show: why this algorithm, why this odd constant, what the external system's quirk is. If you need a comment to explain what a block does, extract a method and name it.</p>\n<h2>7. Keep classes small and cohesive</h2>\n<p>A class should have one reason to change; the fuller treatment is in <a href=\"/library/single-responsibility-principle-java-done-simply\">the single responsibility principle</a>. Signs that a class is too big: many unrelated fields, methods that use disjoint subsets of the fields and a name ending in <code>Manager</code> or <code>Util</code>.</p>\n<h2>8. Depend on abstractions at the edges</h2>\n<p>Code that creates its collaborators with <code>new</code> cannot be tested in isolation. Pass them in through the constructor, as in <a href=\"/library/dependency-injection-really-spring-uses\">dependency injection</a>. Introduce an interface where a second implementation or a test fake is real, and not for every class.</p>\n<h2>9. Test the behavior, then refactor under it</h2>\n<p>Refactoring without tests is guessing. Write tests that describe what the code should do, then change the structure. Tests are also the best documentation of intent; see <a href=\"/library/junit-5-handbook\">the JUnit 5 handbook</a>.</p>\n<h2>10. Do not abstract early</h2>\n<p>Two similar pieces of code are not yet a pattern. Wait for the third, and see what actually varies. A premature abstraction costs more than duplication, because the wrong abstraction is hard to undo.</p>\n<h2>The rules applied to one real method</h2>\n<p>Rules read well on slides and fail on contact with a method that has grown for three years. Here is a realistic one:</p>\n<pre><code class=\"language-java\">public String process(Map&lt;String, Object&gt; data, boolean notify, boolean fast) {\n    String result = null;\n    if (data != null) {\n        if (data.get(\"qty\") != null &amp;&amp; (Integer) data.get(\"qty\") &gt; 0) {\n            Object p = data.get(\"price\");\n            double t = (p == null ? 0 : (Double) p) * (Integer) data.get(\"qty\");\n            if (!fast) {\n                t = t - t * discount((String) data.get(\"cust\"));\n            }\n            repo.save(new Order((String) data.get(\"cust\"), t));\n            if (notify) {\n                mailer.send((String) data.get(\"cust\"), \"Order total \" + t);\n            }\n            result = \"OK\";\n        } else {\n            result = \"BAD\";\n        }\n    } else {\n        result = \"BAD\";\n    }\n    return result;\n}</code></pre>\n<p>Count the problems against the rules: names that say nothing (<code>data</code>, <code>t</code>, <code>p</code>), a map where a type belongs, <code>double</code> for money, two boolean flags, a string result that stands for success or failure, nesting four levels deep, validation, pricing, persistence and notification in one method, and an <code>Object</code> cast the compiler cannot check.</p>\n<h2>The same behavior, cleaned up in steps</h2>\n<p>Introduce a type for the input and validate at the edge, which also gives the domain its own words (rules 1 and 4):</p>\n<pre><code class=\"language-java\">public record PlaceOrder(String customerId, int quantity, Money unitPrice) {\n\n    public PlaceOrder {\n        Objects.requireNonNull(customerId, \"customerId\");\n        Objects.requireNonNull(unitPrice, \"unitPrice\");\n        if (quantity &lt;= 0) {\n            throw new IllegalArgumentException(\"quantity must be positive but was \" + quantity);\n        }\n    }\n\n    Money subtotal() {\n        return unitPrice.times(quantity);\n    }\n}</code></pre>\n<p>Replace the boolean flags with what they mean (rule 5) and return a result type instead of a string (rule 4):</p>\n<pre><code class=\"language-java\">public enum Pricing { STANDARD, PROMOTIONAL }\n\npublic sealed interface OrderResult {\n    record Placed(long orderId, Money total) implements OrderResult {}\n    record Rejected(String reason) implements OrderResult {}\n}</code></pre>\n<p>Now the method reads at one level of abstraction (rule 2), with each step a named operation:</p>\n<pre><code class=\"language-java\">@Transactional\npublic OrderResult place(PlaceOrder request, Pricing pricing) {\n    Money total = priced(request, pricing);\n    Order saved = orders.save(new Order(request.customerId(), total));\n    notifications.orderPlaced(saved);\n    return new OrderResult.Placed(saved.id(), total);\n}\n\nMoney priced(PlaceOrder request, Pricing pricing) {\n    Money subtotal = request.subtotal();\n    return pricing == Pricing.PROMOTIONAL\n        ? subtotal\n        : subtotal.minus(subtotal.times(discounts.rateFor(request.customerId())));\n}</code></pre>\n<p>The caller handles the result with a <code>switch</code> that the compiler checks for completeness, so adding a third outcome later fails the build in every place that forgot it:</p>\n<pre><code class=\"language-java\">String message = switch (service.place(request, Pricing.STANDARD)) {\n    case OrderResult.Placed p -&gt; \"Placed \" + p.orderId();\n    case OrderResult.Rejected r -&gt; \"Rejected: \" + r.reason();\n};</code></pre>\n<h2>Tests first, so the refactoring is safe</h2>\n<p>Rule 9 matters most here. Before touching the old method, pin what it does, including the odd cases, with a characterization test:</p>\n<pre><code class=\"language-java\">class OrderPricingTest {\n\n    @ParameterizedTest\n    @CsvSource({\n        \"10, 5.00, STANDARD,    47.50\",\n        \"10, 5.00, PROMOTIONAL, 50.00\",\n        \"1,  5.00, STANDARD,    4.75\"\n    })\n    void totals(int quantity, String price, Pricing pricing, String expected) {\n        var request = new PlaceOrder(\"cust-1\", quantity, Money.of(price));\n        assertEquals(Money.of(expected), service.priced(request, pricing));\n    }\n\n    @Test\n    void zeroQuantityIsRejectedAtTheEdge() {\n        assertThrows(IllegalArgumentException.class,\n            () -&gt; new PlaceOrder(\"cust-1\", 0, Money.of(\"5.00\")));\n    }\n}</code></pre>\n<p>The numbers above assume a 5 percent customer discount. The test table is also the specification: a product owner can read it and say which rows are wrong, which is a review the original method could never have had.</p>\n<h2>What not to extract</h2>\n<p>The cleaned version has more types, and that is a cost. Resist the urge to go further. A <code>DiscountStrategyFactory</code> with one strategy, an interface with one implementation and no test double, a method extracted whose name restates its body: these add reading cost without adding meaning. A good test for any new abstraction is whether you can write its name without the words \"helper\", \"manager\" or \"util\". If you cannot, the thing has no identity yet, and leaving it inline is the cleaner choice.</p>\n<h2>When these rules do not apply</h2>\n<p>Performance-critical inner loops may trade readability for speed after measurement, and generated code and scripts need not follow them. Rules are in service of change: when following one makes the next change harder, ignore it and say why in a comment. The <a href=\"https://google.github.io/styleguide/javaguide.html\">Google Java Style Guide</a> and the <a href=\"https://docs.oracle.com/javase/specs/jls/se25/html/index.html\">Java Language Specification</a> give formatting and syntax references.</p>","date_published":"2026-11-14T04:09:31+00:00","tags":["Architecture"]},{"id":"https://javahacks.dev/library/whitelabel-error-page-spring-boot-fix","url":"https://javahacks.dev/library/whitelabel-error-page-spring-boot-fix","title":"Fix Spring Boot Whitelabel Error Page 404 Not Found Errors","summary":"Fix the Whitelabel Error Page in Spring Boot by checking component scanning, the mapped path, the context path and the template location.","content_html":"<p>You open a URL on your new application and get this:</p>\n<pre><code class=\"language-text\">Whitelabel Error Page\n\nThis application has no explicit mapping for /error, so you are seeing this as a fallback.\n\nThere was an unexpected error (type=Not Found, status=404).</code></pre>\n<p>Spring MVC tried to find something to handle your request, found nothing and fell back to the error page. The page itself is not the problem; it is the symptom of a missing mapping. The checks below go from most to least likely. The request path is explained in <a href=\"/library/spring-mvc-works-handles-request-filter\">how Spring MVC handles a request</a>, and the project layout in <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a>.</p>\n<h2>Cause 1: the controller is not scanned</h2>\n<p><code>@SpringBootApplication</code> scans its own package and everything below. A controller in a different root package is invisible:</p>\n<pre><code class=\"language-text\">dev.javahacks.shop.ShopApplication          scanned\ndev.javahacks.shop.web.HelloController      scanned\ndev.javahacks.web.HelloController           NOT scanned</code></pre>\n<p>Move the class under the application package, or widen the scan with <code>@SpringBootApplication(scanBasePackages = \"dev.javahacks\")</code>. Moving is better, because the scan then matches the structure.</p>\n<h2>Cause 2: the annotation is missing</h2>\n<p>A class needs <code>@RestController</code> (or <code>@Controller</code> for views) to become a handler:</p>\n<pre><code class=\"language-java\">@RestController\nclass HelloController {\n\n    @GetMapping(\"/hello\")\n    String hello() {\n        return \"hello\";\n    }\n}</code></pre>\n<p>A plain class with <code>@RequestMapping</code> methods and no stereotype is not registered. Also check imports: <code>@GetMapping</code> must come from <code>org.springframework.web.bind.annotation</code>.</p>\n<h2>Cause 3: the path is not the one you typed</h2>\n<p>Check <code>server.servlet.context-path</code> and any class-level <code>@RequestMapping</code>. With <code>server.servlet.context-path=/app</code> and <code>@RequestMapping(\"/api\")</code> on the class, the full URL is <code>/app/api/hello</code>. A trailing slash is not matched by default in Spring Framework 6 and later, so <code>/hello/</code> is a different URL from <code>/hello</code>.</p>\n<h2>Cause 4: a view or a static file is in the wrong place</h2>\n<p>Static files belong in <code>src/main/resources/static</code>, and Thymeleaf templates in <code>src/main/resources/templates</code>. A file in <code>src/main/webapp</code> is ignored in a jar. A controller that returns a view name <code>home</code> needs <code>templates/home.html</code>; a missing template usually gives a 500, not a 404, but the path to the controller can still 404 if the controller itself is not found.</p>\n<h2>Prove it with the mappings endpoint</h2>\n<p>Add Actuator, expose the endpoint and read the list:</p>\n<pre><code class=\"language-properties\">management.endpoints.web.exposure.include=mappings</code></pre>\n<pre><code class=\"language-bash\">curl -s localhost:8080/actuator/mappings | grep -o '\"pattern\":\"[^\"]*\"' | head</code></pre>\n<p>If your path is not in the list, the controller was not registered, which is cause 1 or 2. If it is in the list, you are requesting a different URL. Remove the exposure setting when you are done.</p>\n<h2>Customize the page for production</h2>\n<p>The Whitelabel page leaks that you are running Spring Boot, and a browser user gets nothing useful. Turn it off and provide your own:</p>\n<pre><code class=\"language-properties\">server.error.whitelabel.enabled=false</code></pre>\n<p>Put an <code>error.html</code> template under <code>templates/</code> for HTML clients. For a JSON API, return problem details from a <code>@RestControllerAdvice</code>, as in <a href=\"/library/spring-mvc-rest-api-guide-building\">building REST APIs with Spring MVC</a>.</p>\n<h2>Cause 5: the web starter is missing or the wrong one is on the classpath</h2>\n<p>A project that has <code>spring-boot-starter-web</code> has Spring MVC. One that has only <code>spring-boot-starter-webflux</code> runs the reactive stack, which also supports annotated controllers but handles static files and templates differently. A project with both runs MVC unless the application type is set. If a controller works in one project and 404s in another that looks identical, compare <code>./mvnw dependency:tree | grep starter</code> between them, and check the startup log for the line naming the embedded server and the stack.</p>\n<h2>Cause 6: static content is disabled or mapped elsewhere</h2>\n<p>Boot serves <code>static/</code>, <code>public/</code>, <code>resources/</code> and <code>META-INF/resources/</code> from the classpath at the root of the context. Two settings change that:</p>\n<pre><code class=\"language-properties\">spring.web.resources.add-mappings=false\nspring.mvc.static-path-pattern=/assets/**</code></pre>\n<p>The first turns static serving off completely, so <code>index.html</code> stops being the welcome page. The second moves it, so a file at <code>static/logo.png</code> is now at <code>/assets/logo.png</code>. A <code>@EnableWebMvc</code> annotation on any configuration class switches off Boot's MVC auto-configuration altogether, and the usual symptom is the Whitelabel page for a URL that used to serve a file.</p>\n<h2>A test that catches the missing mapping</h2>\n<p>A 404 found in the browser can be found in the build. A slice test loads only the web layer and asserts the route exists:</p>\n<pre><code class=\"language-java\">@WebMvcTest(HelloController.class)\nclass HelloControllerTest {\n\n    @Autowired\n    MockMvc mvc;\n\n    @Test\n    void helloIsMapped() throws Exception {\n        mvc.perform(get(\"/hello\"))\n           .andExpect(status().isOk())\n           .andExpect(content().string(\"hello\"));\n    }\n}</code></pre>\n<p>If the controller is not scanned or the path is wrong, the test fails with <code>Status expected:&lt;200&gt; but was:&lt;404&gt;</code>. Run it before the first deploy and the page never reaches a user. For the full application context, <code>@SpringBootTest</code> with <code>@AutoConfigureMockMvc</code> gives the same assertion with security and filters included.</p>\n<h2>Reading the page's status line</h2>\n<p>The Whitelabel page prints a type and a status, and the status separates the causes.</p>\n<table><thead><tr><th>Status on the page</th><th>Meaning</th><th>Where to look</th></tr></thead><tbody><tr><td>404 Not Found</td><td>No handler matched</td><td>Scan, annotations, path, context path</td></tr><tr><td>405 Method Not Allowed</td><td>Path matched, HTTP method did not</td><td><code>@GetMapping</code> against the verb used</td></tr><tr><td>400 Bad Request</td><td>Binding or a missing parameter failed</td><td>The log line from <code>DefaultHandlerExceptionResolver</code></td></tr><tr><td>500 Internal Server Error</td><td>A handler threw</td><td>The stack trace in the log</td></tr><tr><td>403 Forbidden</td><td>Spring Security rejected it</td><td>Security configuration, CSRF on a POST</td></tr></tbody></table>\n<p>A 405 deserves its own mention, because it is the one that makes a correct path look wrong. A form that submits a POST to a <code>@GetMapping</code> handler produces a Whitelabel page with <code>Method Not Allowed</code>, and nothing on it mentions the verb unless the message is shown.</p>\n<h2>Show a reason during development</h2>\n<p>By default the error attributes hide the message and the trace. For local work, turn them on and turn them off again before release:</p>\n<pre><code class=\"language-properties\">server.error.include-message=always\nserver.error.include-stacktrace=on_param</code></pre>\n<p>With <code>on_param</code>, appending <code>?trace=true</code> to a URL includes the trace, so it is available on demand without being the default. Do not enable <code>always</code> on a public service, because a trace discloses class names, library versions and sometimes SQL.</p>\n<h2>DevTools and stale classes</h2>\n<p>A controller added while DevTools is running is picked up by the restart classloader, and a controller moved to a new package may not be. If the mappings endpoint is missing a handler that is plainly in the source, stop the application and start it again from a clean build. The same applies to a template that was added after the jar was built, because the running jar cannot see files that were not packaged into it.</p>\n<h2>Where this does not apply</h2>\n<p>A 404 from a reverse proxy or an ingress shows the proxy's page, not the Whitelabel one. If you see the Whitelabel page with status 500, the cause is an exception, not a missing route, so read the log. The <a href=\"https://docs.spring.io/spring-boot/reference/web/servlet.html\">Spring Boot web reference</a> documents the error handling properties. The <a href=\"https://docs.spring.io/spring-boot/how-to/index.html\">Spring Boot how-to guides</a> documents the behavior in detail.</p>","date_published":"2026-11-14T04:08:31+00:00","tags":["Spring Boot"]},{"id":"https://javahacks.dev/library/failed-configure-datasource-fix-spring-boot","url":"https://javahacks.dev/library/failed-configure-datasource-fix-spring-boot","title":"Fix Spring Boot Failed to Configure a DataSource Error","summary":"Fix the Spring Boot DataSource startup failure by checking the URL, the driver, the active profile and whether the application should have a database at all.","content_html":"<p>The report appears before the first request, and it looks like this:</p>\n<pre><code class=\"language-text\">***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nFailed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.\n\nReason: Failed to determine a suitable driver class\n\nAction:\n\nConsider the following:\n\tIf you want an embedded database (H2, HSQL or Derby), please put it on the classpath.\n\tIf you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).</code></pre>\n<p>Spring Boot found <code>spring-boot-starter-data-jpa</code> or a JDBC starter, tried to build a <code>DataSource</code> and had no URL. The causes are short, and the order below goes from the most common. The setup this belongs to is in <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a>.</p>\n<h2>Cause 1: the URL is not set</h2>\n<p>Check that the property exists where Spring Boot looks:</p>\n<pre data-filename=\"src/main/resources/application.properties\"><code class=\"language-properties\">spring.datasource.url=jdbc:postgresql://localhost:5432/shop\nspring.datasource.username=shop\nspring.datasource.password=change-me</code></pre>\n<p>Typos are the usual reason: <code>spring.datasource.jdbc-url</code> is a HikariCP property used when you define your own <code>DataSource</code> bean, and <code>spring.datasource.url</code> is the one auto-configuration reads.</p>\n<h2>Cause 2: the profile that holds the URL is not active</h2>\n<p>The message says \"no profiles are currently active\" for a reason. If your URL lives in <code>application-prod.yaml</code>, nothing reads it until you run with <code>--spring.profiles.active=prod</code> or set <code>SPRING_PROFILES_ACTIVE=prod</code>. Print what is active at startup: the first log lines say <code>The following 1 profile is active: \"prod\"</code> or <code>No active profile set, falling back to 1 default profile: \"default\"</code>.</p>\n<h2>Cause 3: a test resource shadows your main configuration</h2>\n<p>If <code>src/test/resources/application.properties</code> exists, it replaces the main file on the test classpath rather than adding to it. A test that fails with this message while the app runs fine is usually this. Put test-only overrides in <code>application-test.properties</code> with <code>@ActiveProfiles(\"test\")</code>, or use Testcontainers with <code>@ServiceConnection</code> so no URL is needed, as in <a href=\"/library/java-testing-strategy-practical\">a practical testing strategy</a>.</p>\n<h2>Cause 4: the environment variable is spelled wrong</h2>\n<p>Relaxed binding maps <code>SPRING_DATASOURCE_URL</code> to <code>spring.datasource.url</code>. It does not map <code>DATASOURCE_URL</code> or <code>SPRING_DATASOURCE_JDBC_URL</code>. In Kubernetes and Docker, an unset variable that you reference as <code>${DB_URL}</code> in the file turns into <a href=\"/library/could-not-resolve-placeholder-fix-spring\">a different error</a>.</p>\n<h2>Cause 5: the driver is missing</h2>\n<p>With a URL but no driver on the classpath, the reason line changes to <code>Failed to determine a suitable driver class</code> or the connection fails with a different exception. Add the driver, for PostgreSQL <code>org.postgresql:postgresql</code> with <code>runtime</code> scope. If the failure is a connection problem rather than a configuration one, see <a href=\"/library/psqlexception-connection-refused-fix-port-5432\">connection refused on port 5432</a>.</p>\n<h2>When there should be no database</h2>\n<p>Some applications pull in JPA transitively and do not need a database, for example a command-line tool built from a shared module. Remove the starter, or exclude the auto-configuration:</p>\n<pre><code class=\"language-properties\">spring.autoconfigure.exclude=org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration</code></pre>\n<p>The package of that class moved when Spring Boot 4 split auto-configuration into modules, so let your IDE complete the name for the version you use. Excluding it hides the symptom, so do it only when you are sure.</p>\n<h2>Test the connection outside Spring</h2>\n<p>When the URL looks right and the failure continues, separate Spring from the database. A plain JDBC connection answers whether the URL, the driver and the credentials work at all:</p>\n<pre><code class=\"language-java\">try (Connection c = DriverManager.getConnection(url, user, password)) {\n    System.out.println(c.getMetaData().getDatabaseProductName());\n}</code></pre>\n<p>Run it from a scratch class with the same classpath as the application. A <code>No suitable driver</code> message means the driver jar is absent or the URL prefix is wrong, and a <code>Communications link failure</code> or <code>Connection refused</code> means the database is not reachable from where the code runs. In a container, <code>localhost</code> is the container itself, so a URL that works on a laptop points nowhere in the cluster.</p>\n<h2>The URL formats that are easy to get wrong</h2>\n<table><thead><tr><th>Database</th><th>URL shape</th><th>Common mistake</th></tr></thead><tbody><tr><td>PostgreSQL</td><td><code>jdbc:postgresql://host:5432/shop</code></td><td>Missing <code>jdbc:</code> prefix, or <code>postgres://</code> copied from a connection string</td></tr><tr><td>MySQL</td><td><code>jdbc:mysql://host:3306/shop</code></td><td>Using <code>mariadb</code> driver with a <code>mysql</code> URL</td></tr><tr><td>SQL Server</td><td><code>jdbc:sqlserver://host:1433;databaseName=shop</code></td><td>A slash and not a semicolon before the database name</td></tr><tr><td>H2 in memory</td><td><code>jdbc:h2:mem:testdb</code></td><td>The H2 jar is <code>test</code> scope, so it vanishes at runtime</td></tr><tr><td>Oracle</td><td><code>jdbc:oracle:thin:@//host:1521/service</code></td><td>Using a SID where a service name is needed</td></tr></tbody></table>\n<p>A hosted database often gives a URL starting with <code>postgres://</code> or <code>postgresql://user:pass@host/db</code>. That is not a JDBC URL. Split it into <code>spring.datasource.url</code>, <code>username</code> and <code>password</code>.</p>\n<h2>Read the conditions report</h2>\n<p>When nothing in the configuration looks wrong, ask Boot why it did not configure a data source. The report names the condition that failed:</p>\n<pre><code class=\"language-bash\">java -jar app.jar --debug 2&gt;&amp;1 | grep -A6 'DataSourceAutoConfiguration'</code></pre>\n<p>The negative matches section says, for example, <code>DataSourceAutoConfiguration did not match: @ConditionalOnClass did not find required class 'javax.sql.DataSource'</code>, or <code>no embedded database</code>. This line says whether the class is on the classpath and whether a URL was seen. It saves guessing between a missing property and a missing dependency.</p>\n<h2>A dependency that pulls in a database requirement</h2>\n<p><code>spring-boot-starter-data-jpa</code>, <code>spring-boot-starter-jdbc</code> and <code>spring-boot-starter-batch</code> all expect a data source. A project that adds one of them for a minor reason, such as a shared library, gets this error without ever using a database. Search the dependency tree for the starter that brought the requirement in:</p>\n<pre><code class=\"language-bash\">./mvnw dependency:tree | grep -E 'starter-(jdbc|data-jpa|batch)'</code></pre>\n<p>If the application needs no database, remove the starter. If it needs the starter for a library but not the database, exclude the auto-configuration:</p>\n<pre><code class=\"language-properties\">spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration</code></pre>\n<p>Use the exclusion rarely. A service that excludes the data source to start and then fails on the first query has only moved the error.</p>\n<h2>Local services that are not running</h2>\n<p>A Compose file starts the database, and the application starts first and fails because the port is not open yet. Use a health check and make the application wait, or let Spring Boot's Docker Compose support manage the order, as described in <a href=\"/library/spring-boot-docker-compose-support-use\">Docker Compose support</a>. The symptom differs from this post's error, with a connection refused after the URL was read, and the cause is the same class of mistake: the configuration is fine and the environment around it is not ready.</p>\n<h2>What this does not cover</h2>\n<p>This report is about configuration. If the pool starts and then requests fail, you have a <a href=\"/library/connection-not-available-request-timed-out\">connection pool timeout</a>, not a missing DataSource. The <a href=\"https://docs.spring.io/spring-boot/reference/data/sql.html\">Spring Boot data access reference</a> lists every <code>spring.datasource.*</code> property and how the pool is selected. The <a href=\"https://docs.spring.io/spring-boot/how-to/index.html\">Spring Boot how-to guides</a> documents the behavior in detail.</p>","date_published":"2026-11-14T04:07:31+00:00","tags":["Spring Boot"]},{"id":"https://javahacks.dev/library/could-not-resolve-placeholder-fix-spring","url":"https://javahacks.dev/library/could-not-resolve-placeholder-fix-spring","title":"Fix Could Not Resolve Placeholder in Spring Boot Value","summary":"Fix the Spring error about an unresolvable placeholder by checking the property name, the active profile, test resources and environment variable names.","content_html":"<p>The context fails to start and the cause is one line:</p>\n<pre><code class=\"language-text\">java.lang.IllegalArgumentException: Could not resolve placeholder 'app.api-key' in value \"${app.api-key}\"</code></pre>\n<p>A field annotated with <code>@Value(\"${app.api-key}\")</code> or a property file referencing <code>${app.api-key}</code> has no value to substitute. Spring resolves those placeholders while building the bean, so the application refuses to start rather than run with a hole in its configuration. That is the behavior you want. This post covers the cases in the order they happen. Configuration sources are explained in <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a>.</p>\n<h2>Cause 1: the property is not defined, or is spelled differently</h2>\n<pre><code class=\"language-java\">@Value(\"${app.api-key}\")\nprivate String apiKey;</code></pre>\n<pre data-filename=\"src/main/resources/application.properties\"><code class=\"language-properties\">app.apikey=secret</code></pre>\n<p><code>app.api-key</code> and <code>app.apikey</code> are different keys in a <code>@Value</code> expression. Pick one spelling and match it. Prefer a typed <code>@ConfigurationProperties</code> class, which also validates and tolerates different forms in the file; see <a href=\"/library/spring-boot-application-failed-start-fix\">binding failures in application failed to start</a>.</p>\n<h2>Cause 2: it is defined in a profile that is not active</h2>\n<p>A key in <code>application-prod.properties</code> does not exist when the active profile is <code>dev</code>. Check which profiles are active in the first log lines. Run with <code>--spring.profiles.active=prod</code> or set <code>SPRING_PROFILES_ACTIVE</code>.</p>\n<h2>Cause 3: a test resource hides the main file</h2>\n<p>If <code>src/test/resources/application.properties</code> exists, it takes the place of <code>src/main/resources/application.properties</code> for tests; the two do not merge. A test that fails with this error while the application runs is nearly always this. Put test overrides in <code>application-test.properties</code>, or inline them:</p>\n<pre><code class=\"language-java\">@SpringBootTest(properties = \"app.api-key=test-key\")\nclass BillingServiceTest { }</code></pre>\n<h2>Cause 4: the environment variable has the wrong name</h2>\n<p>Relaxed binding turns <code>APP_API_KEY</code> into <code>app.api-key</code>. These do not work: <code>API_KEY</code>, <code>APP.API.KEY</code> in some shells, <code>app-api-key</code>. In a container, confirm the variable reached the process:</p>\n<pre><code class=\"language-bash\">docker exec shop env | grep APP_</code></pre>\n<p>For Kubernetes, check the pod spec's <code>env</code> or <code>envFrom</code> and whether the Secret or ConfigMap exists in the namespace.</p>\n<h2>Cause 5: a placeholder inside a property value</h2>\n<p>Spring also resolves <code>${...}</code> inside values:</p>\n<pre><code class=\"language-properties\">app.report-url=${app.base-url}/reports</code></pre>\n<p>If <code>app.base-url</code> is missing, the error names <code>app.base-url</code> and not <code>app.report-url</code>. Read the key in the message, not the line that failed first.</p>\n<h2>Defaults and when to use them</h2>\n<pre><code class=\"language-java\">@Value(\"${app.page-size:20}\")\nprivate int pageSize;</code></pre>\n<p>The part after the colon is used when the key is absent. That is right for a tuning parameter with a safe default. It is wrong for a credential or a URL, where a silent empty value turns a startup failure into a runtime failure in front of users. For secrets, fail on purpose.</p>\n<h2>Know where Spring looked</h2>\n<p>The error names the key and says nothing about the places searched. The sources are checked in a fixed order, and the first match wins: command line arguments, <code>SPRING_APPLICATION_JSON</code>, Java system properties, operating system environment variables, then <code>application-{profile}</code> files, then <code>application</code> files, and finally <code>@PropertySource</code> and defaults. The full list is in <a href=\"/library/spring-boot-configuration-precedence-externalized-order\">configuration precedence</a>. To see what the running application can resolve, ask the <code>Environment</code> in a test:</p>\n<pre><code class=\"language-java\">@SpringBootTest\nclass ConfigTest {\n\n    @Autowired\n    Environment env;\n\n    @Test\n    void apiKeyIsConfigured() {\n        assertThat(env.getProperty(\"app.api-key\")).isNotBlank();\n    }\n}</code></pre>\n<p>A test that fails with the same message as the application proves that the problem is in the configuration, and not in the way the application is launched.</p>\n<h2>Fail at startup with a clear message</h2>\n<p>A <code>@Value</code> placeholder fails the whole context with a stack trace, which an operator may not read quickly. Binding to a validated properties class reports each missing value by name:</p>\n<pre><code class=\"language-java\">@ConfigurationProperties(prefix = \"app\")\n@Validated\nrecord AppProperties(@NotBlank String apiKey, @Min(1) int timeoutSeconds) { }</code></pre>\n<p>Boot refuses to start with <code>Binding to target ... failed</code> and a list of the failed properties, <code>app.api-key</code> among them. The failure is still at startup, and the message tells the person who deploys what to fix. This is the form to use for anything required. See <a href=\"/library/spring-boot-configurationproperties-bind-configuration\">binding configuration</a>.</p>\n<h2>Supplying a default, and when not to</h2>\n<p>A default after a colon removes the error, and it also removes the safety:</p>\n<pre><code class=\"language-java\">@Value(\"${app.page-size:20}\")\nint pageSize;</code></pre>\n<p>That is right for a tuning knob with a sensible value. It is wrong for a credential, a URL of another service or a feature switch with consequences. A missing database password with a default of an empty string produces an authentication error at the first query, which is later and further from the cause than the placeholder error. Use defaults for optional values only.</p>\n<h2>A resolver that ignores the problem</h2>\n<p>Spring has a switch to leave unresolved placeholders as literal text, <code>ignoreUnresolvablePlaceholders</code> on <code>PropertySourcesPlaceholderConfigurer</code>. It is meant for a second configurer in a layered context, and turning it on to silence this error means a request that later sends the string <code>${app.api-key}</code> to a remote API as the key. Treat the error as correct and fix the property.</p>\n<h2>Quick diagnosis by environment</h2>\n<table><thead><tr><th>Where it fails</th><th>What to check</th></tr></thead><tbody><tr><td>Only in the IDE</td><td>The run configuration's active profiles and working directory</td></tr><tr><td>Only in tests</td><td>A <code>src/test/resources</code> file that shadows the main one</td></tr><tr><td>Only in the container</td><td>Environment variable name, the mounted config path, the active profile</td></tr><tr><td>Only on CI</td><td>Secrets not exposed to the job, forks do not receive them</td></tr><tr><td>Only after a rename</td><td>A stale value in a deployment manifest using the old key</td></tr></tbody></table>\n<p>The container row accounts for most production cases. The application starts on a laptop with a local file and in the cluster with none, and the placeholder error is the first sign that the manifest never supplied the value.</p>\n<h2>A configuration checklist for new properties</h2>\n<p>Most placeholder errors arrive with a new property. Adding one takes four steps, and skipping any is a future incident: add the key to the main configuration with a default or an empty marker and a comment, add it to the test configuration, add it to the deployment manifests of every environment, and add a line to the README. The properties class with validation then fails at startup in any environment that missed the third step.</p>\n<p>A CI check can compare the keys referenced in code against the keys defined in the manifests, using a short script over <code>application.yml</code> and the deployment files. It finds the missing one on the pull request, when the author remembers the context.</p>\n<h2>Where this does not apply</h2>\n<p>A <code>${...}</code> that must stay literal, for example in a message template or a Thymeleaf string, should not be a Spring placeholder; escape it or move it out of the property source. If a non-string property fails to convert instead, you have a binding error, not a placeholder error. The <a href=\"https://docs.spring.io/spring-boot/reference/features/external-config.html\">externalized configuration reference</a> lists the order in which sources override each other, and [<code>UnsatisfiedDependencyException</code>](/library/unsatisfieddependencyexception-fix-spring) is the wrapper this error often arrives inside. The <a href=\"https://docs.spring.io/spring-boot/how-to/index.html\">Spring Boot how-to guides</a> documents the behavior in detail.</p>","date_published":"2026-11-14T04:06:31+00:00","tags":["Spring Boot"]},{"id":"https://javahacks.dev/library/failed-load-applicationcontext-fix-spring-boot","url":"https://javahacks.dev/library/failed-load-applicationcontext-fix-spring-boot","title":"Fix Spring Boot Test Failed to Load ApplicationContext","summary":"Find why a Spring Boot test cannot load its ApplicationContext, from a missing configuration class to a missing bean, property or database.","content_html":"<p>The test fails before its first line runs:</p>\n<pre><code class=\"language-text\">java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@1a2b3c testClass = dev.javahacks.shop.OrderControllerTest, ...]\n\tat org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(...)\nCaused by: org.springframework.beans.factory.UnsatisfiedDependencyException: ...</code></pre>\n<p>Spring tries to start an application context for the test, and building it failed. This post lists the causes in the order to check them. The structure of the tests is described in <a href=\"/library/java-testing-strategy-practical\">a practical Java testing strategy</a>, and the application side in <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a>.</p>\n<h2>Read the last Caused by</h2>\n<p>Everything above it is the route Spring took. The innermost exception names the real problem, and the usual ones map to a section below:</p>\n<table><thead><tr><th>Innermost message</th><th>Section</th></tr></thead><tbody><tr><td>Unable to find a <code>@SpringBootConfiguration</code></td><td>Cause 1</td></tr><tr><td>No qualifying bean of type</td><td>Cause 2</td></tr><tr><td>Could not resolve placeholder</td><td>Cause 3</td></tr><tr><td>Failed to configure a DataSource, connection refused</td><td>Cause 4</td></tr></tbody></table>\n<h2>Cause 1: Spring cannot find the application class</h2>\n<pre><code class=\"language-text\">java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration by searching packages up from test class 'dev.javahacks.tests.OrderTest'. You need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test</code></pre>\n<p>Spring looks for the <code>@SpringBootApplication</code> class by walking up from the test's package. A test in <code>dev.javahacks.tests</code> cannot find an application in <code>dev.javahacks.shop</code>. Move the test into the application's package tree, or name the class:</p>\n<pre><code class=\"language-java\">@SpringBootTest(classes = ShopApplication.class)\nclass OrderTest { }</code></pre>\n<h2>Cause 2: a slice does not load the bean</h2>\n<pre><code class=\"language-java\">@WebMvcTest(OrderController.class)\nclass OrderControllerTest {\n    // OrderController needs OrderService, which @WebMvcTest does not load\n}</code></pre>\n<p>Provide the collaborator:</p>\n<pre><code class=\"language-java\">@MockitoBean OrderService orders;</code></pre>\n<p>For <code>@DataJpaTest</code>, services are not loaded either; import what you need with <code>@Import(OrderRepositoryAdapter.class)</code>. The same message in a running application is <a href=\"/library/no-qualifying-bean-type-fix-spring\">no qualifying bean of type</a>.</p>\n<h2>Cause 3: a property is missing</h2>\n<p>A test resource named <code>application.properties</code> or <code>application.yaml</code> replaces the main file on the test classpath. Properties that the application needs vanish. Rename the test file <code>application-test.properties</code>, activate it with <code>@ActiveProfiles(\"test\")</code>, or set values inline:</p>\n<pre><code class=\"language-java\">@SpringBootTest(properties = \"shop.currency=USD\")</code></pre>\n<p>See the <a href=\"/library/could-not-resolve-placeholder-fix-spring\">placeholder fix</a> for the full list of reasons.</p>\n<h2>Cause 4: the database is not there</h2>\n<p>A full <code>@SpringBootTest</code> starts every auto-configured component, including the <code>DataSource</code>. Without a URL or a reachable database it fails. Use a Testcontainers PostgreSQL with <code>@ServiceConnection</code>, or exclude the data auto-configuration for tests that do not need it. A test that fails here only in CI is often missing Docker: <a href=\"/library/could-not-find-valid-docker-environment\">Could not find a valid Docker environment</a>.</p>\n<h2>Context caching can move the failure</h2>\n<p>Spring caches contexts between test classes by their configuration. A class that adds <code>@MockitoBean</code> or a <code>@TestPropertySource</code> creates a new context, and the cache keeps the old ones. If one context fails to build, the next class using the same configuration reports the same failure, which makes it look like many tests are broken when one setup is. Fix the first failure in the run.</p>\n<h2>Run one test alone</h2>\n<pre><code class=\"language-bash\">./mvnw -q test -Dtest=OrderControllerTest</code></pre>\n<p>If it passes alone and fails in the full run, a different test is changing shared state: a static field, a port, a file. Look for <code>@DirtiesContext</code>, which discards the cache and slows the suite; use it only when a test truly modifies the context.</p>\n<h2>Give the test a configuration that exists</h2>\n<p>A test that cannot find the application class fails in the first step. Name it, or move the test into the same package tree:</p>\n<pre><code class=\"language-java\">@SpringBootTest(classes = ShopApplication.class)\n@ActiveProfiles(\"test\")\nclass OrderControllerTest { }</code></pre>\n<p><code>@ActiveProfiles(\"test\")</code> loads <code>application-test.properties</code> on top of the main file, which is the right place for test overrides. A test whose package is outside the application's package is the other cause of the missing configuration, and the error then names <code>Unable to find a @SpringBootConfiguration</code>. The test's package should be the same or below the package of the class with <code>@SpringBootApplication</code>.</p>\n<h2>Supply properties and containers to the test</h2>\n<p>A test that needs a value that production gets from the environment can set it in the annotation or compute it at startup:</p>\n<pre><code class=\"language-java\">@SpringBootTest(properties = \"app.api-key=test-key\")\nclass ClientTest { }\n\n@Testcontainers\n@SpringBootTest\nclass RepositoryTest {\n\n    @Container\n    static PostgreSQLContainer&lt;?&gt; db = new PostgreSQLContainer&lt;&gt;(\"postgres:17\");\n\n    @DynamicPropertySource\n    static void datasource(DynamicPropertyRegistry registry) {\n        registry.add(\"spring.datasource.url\", db::getJdbcUrl);\n        registry.add(\"spring.datasource.username\", db::getUsername);\n        registry.add(\"spring.datasource.password\", db::getPassword);\n    }\n}</code></pre>\n<p>The registry accepts suppliers, so the properties are read after the container has started and its port is known. With Spring Boot 3.1 and later, <code>@ServiceConnection</code> replaces those lines for the common containers.</p>\n<h2>Slices and what they leave out</h2>\n<p>A slice loads a part of the context, and any bean outside it is missing unless you provide it. <code>@WebMvcTest</code> loads controllers, filters and converters, and no services or repositories. A controller that depends on a service fails with <code>NoSuchBeanDefinitionException</code> until the test supplies one:</p>\n<pre><code class=\"language-java\">@WebMvcTest(OrderController.class)\nclass OrderControllerTest {\n\n    @MockitoBean\n    OrderService service;\n}</code></pre>\n<p>The mock fills the gap. A test with ten missing beans is a sign that the slice is the wrong tool, and <code>@SpringBootTest</code> with a real or fake service layer is better.</p>\n<h2>See the whole cause chain</h2>\n<p>The first lines of the exception are the same for every cause. The explanation is at the bottom. Surefire writes each test's full output to a file:</p>\n<pre><code class=\"language-bash\">grep -n 'Caused by' target/surefire-reports/*OrderControllerTest.txt | tail -5</code></pre>\n<p>The last <code>Caused by</code> names the real problem, such as a missing property, an unsatisfied bean or a refused database connection. When only the summary is printed, rerun the one test with <code>-Dsurefire.useFile=false</code> to see the full trace in the console. For more detail on how the context was assembled, turn on <code>logging.level.org.springframework.test.context=DEBUG</code>.</p>\n<h2>Cached contexts hide and move failures</h2>\n<p>Spring caches a context between test classes that share the same configuration, so the first class to need it pays the cost and reports the failure. A different mix of properties, mocks or profiles creates a new context, and a suite can fail in a test unrelated to the change. <code>@MockitoBean</code> and <code>@DirtiesContext</code> both force new contexts. A suite with thirty distinct configurations starts thirty contexts and is slow, so group tests with the same setup, and prefer one shared base configuration.</p>\n<table><thead><tr><th>Cause of a new context</th><th>How to avoid it</th></tr></thead><tbody><tr><td>Different <code>@MockitoBean</code> sets</td><td>Put common mocks in a shared abstract class</td></tr><tr><td><code>@DirtiesContext</code> on a method</td><td>Reset state in <code>@BeforeEach</code> instead</td></tr><tr><td>Different <code>properties</code> strings</td><td>Use one <code>application-test.properties</code></td></tr><tr><td>Different active profiles</td><td>Standardise on one test profile</td></tr></tbody></table>\n<p>When one test passes alone and fails in the suite, an earlier test changed shared state, and the context cache is the first suspect.</p>\n<h2>A smoke test that guards the context</h2>\n<p>One test that starts the full context with the test profile is worth having in every project. It is quick to write, and it fails at once when someone adds a bean with a missing dependency or a property with no value. Run it first in the pipeline, ahead of the slower suites, so a wiring break fails the build in a minute and not after a long run.</p>\n<p>Keep the test profile complete: every required property has a harmless value there, so a new required property forces a conscious edit to the test configuration.</p>\n<h2>Where this does not apply</h2>\n<p>If the context loads and a test fails, the problem is the test. If the error mentions an <code>ApplicationContext</code> in a non-Spring Boot project, check <code>@ContextConfiguration</code> and the XML or Java configuration location. The <a href=\"https://docs.spring.io/spring-boot/reference/testing/index.html\">Spring Boot testing reference</a> lists the slices and what each one loads, and the <a href=\"https://docs.spring.io/spring-framework/reference/testing/testcontext-framework.html\">Spring TestContext framework reference</a> explains caching.</p>","date_published":"2026-11-14T04:05:31+00:00","tags":["Testing"]},{"id":"https://javahacks.dev/library/spring-boot-docker-image-not-starting","url":"https://javahacks.dev/library/spring-boot-docker-image-not-starting","title":"Fix a Spring Boot Docker Image That Will Not Start","summary":"Fix a Spring Boot container that exits at once by reading its logs and checking the Java version, jar path, architecture, configuration and memory limit.","content_html":"<p>The image builds, <code>docker run</code> returns to the prompt a second later, and the container is gone. Or it stays up and never answers on its port. A Spring Boot image that will not start fails in a handful of ways, and each prints a distinctive line if you know where to look. The first move is always the same: read what the container said before it died. Then match the message to one of eight causes: a Java version that is too old for the jar, a jar that is not where <code>ENTRYPOINT</code> expects it, a jar with no main class, a CPU architecture mismatch, configuration that exists on your laptop and not in the container, a port conflict, a memory limit and file permissions. This post walks through them with the exact messages and fixes, then shows how to get a shell inside the image to look around. Examples use Docker 27, Spring Boot 4 and JDK 25.</p>\n<p>Start with the logs of the failed container, which Docker keeps until you remove it:</p>\n<pre><code class=\"language-bash\">docker run --name shop shop:1.0.0\ndocker logs shop\ndocker inspect shop --format '{{.State.ExitCode}} {{.State.OOMKilled}}'</code></pre>\n<pre><code class=\"language-text\">1 false</code></pre>\n<p>The exit code is the first clue (<code>1</code> the application or JVM failed, <code>137</code> killed, <code>126</code> or <code>127</code> command problem, <code>0</code> finished normally) and the <code>OOMKilled</code> flag settles whether memory was the cause. The [<code>docker logs</code> reference](https://docs.docker.com/reference/cli/docker/container/logs/) covers the options. Then read the first error in the log, not the last.</p>\n<h2>Cause 1: the Java version is too old</h2>\n<p>The jar was compiled for a newer Java than the image provides:</p>\n<pre><code class=\"language-text\">Error: LinkageError occurred while loading main class dev.javahacks.shop.ShopApplication\n\tjava.lang.UnsupportedClassVersionError: dev/javahacks/shop/ShopApplication has been compiled by a more recent version of the Java Runtime (class file version 69.0), this version of the Java Runtime only recognizes class file versions up to 61.0</code></pre>\n<p>Class file version 69 is Java 25, and 61 is Java 17. Match the runtime image to the build: if the build uses JDK 25, the image must be <code>eclipse-temurin:25-jre</code>, not <code>17</code>. Check what the image actually contains rather than the tag you meant:</p>\n<pre><code class=\"language-bash\">docker run --rm shop:1.0.0 java -version</code></pre>\n<p>The conversion table of class file versions and the full fix are in <a href=\"/library/unsupportedclassversionerror-fix-class-file-version-mismatch\">UnsupportedClassVersionError</a>. A multi-stage Dockerfile whose build and run stages use different JDKs is the usual source.</p>\n<h2>Cause 2: the jar is not where ENTRYPOINT says</h2>\n<pre><code class=\"language-text\">Error: Unable to access jarfile /app/app.jar</code></pre>\n<p>The <code>ENTRYPOINT</code> points at a path that does not exist in the image. Typical mistakes: the jar name includes a version (<code>shop-1.0.0.jar</code>) while the <code>COPY</code> or <code>ENTRYPOINT</code> uses <code>app.jar</code>; a wildcard that matches two files; the <code>COPY</code> source path is relative to the build context and the file is outside it or excluded by <code>.dockerignore</code>; a multi-stage build copies from the wrong stage. List the image's files:</p>\n<pre><code class=\"language-bash\">docker run --rm --entrypoint sh shop:1.0.0 -c 'ls -l /app'</code></pre>\n<pre><code class=\"language-text\">total 62144\n-rw-r--r-- 1 root root 63631360 Nov  6 09:30 shop-1.0.0.jar</code></pre>\n<p>The file is <code>shop-1.0.0.jar</code>; the entrypoint wanted <code>app.jar</code>. Fix the name in one place, ideally by setting <code>finalName</code> in the build or copying with an explicit target name (<code>COPY --from=build /src/target/shop-*.jar /app/app.jar</code>, with a single match). Ensure <code>.dockerignore</code> does not exclude <code>target/</code>, if the Dockerfile copies a prebuilt jar. The Dockerfile patterns that avoid this are in <a href=\"/library/java-dockerfile-write-right-way\">writing a Java Dockerfile the right way</a>.</p>\n<h2>Cause 3: no main manifest attribute</h2>\n<pre><code class=\"language-text\">no main manifest attribute, in /app/app.jar</code></pre>\n<p>The jar is not an executable Spring Boot jar. It is the plain library jar, which Maven produces before the Boot plugin repackages it, or the Boot plugin is missing from the build. Check the manifest:</p>\n<pre><code class=\"language-bash\">unzip -p target/shop-1.0.0.jar META-INF/MANIFEST.MF | grep -E 'Main-Class|Start-Class'</code></pre>\n<pre><code class=\"language-text\">Main-Class: org.springframework.boot.loader.launch.JarLauncher\nStart-Class: dev.javahacks.shop.ShopApplication</code></pre>\n<p>A Boot executable jar has <code>Main-Class: ...JarLauncher</code> and a <code>Start-Class</code>. If both are absent, add the Spring Boot Maven plugin with the <code>repackage</code> goal (it is part of the parent POM's lifecycle when you use <code>spring-boot-starter-parent</code>), and copy the repackaged jar, not <code>*.jar.original</code>:</p>\n<pre data-filename=\"pom.xml\"><code class=\"language-xml\">&lt;plugin&gt;\n  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;\n  &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;\n&lt;/plugin&gt;</code></pre>\n<p>A related message, <code>Unable to find a suitable main class</code>, is raised at build time and is covered in <a href=\"/library/unable-find-suitable-main-class-fix\">fixing unable to find suitable main class</a>. Another option that avoids the Dockerfile entirely is building the image with the plugin: <code>mvn spring-boot:build-image</code>, described in the <a href=\"https://docs.spring.io/spring-boot/reference/packaging/container-images/index.html\">container images reference</a>.</p>\n<h2>Cause 4: architecture mismatch</h2>\n<pre><code class=\"language-text\">exec /opt/java/openjdk/bin/java: exec format error</code></pre>\n<p>or the warning <code>The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)</code>. The image was built for a different CPU architecture than the machine runs: an image built on an Apple Silicon laptop (arm64) pushed to an amd64 cluster, or the reverse. Check:</p>\n<pre><code class=\"language-bash\">docker image inspect shop:1.0.0 --format '{{.Os}}/{{.Architecture}}'</code></pre>\n<pre><code class=\"language-text\">linux/arm64</code></pre>\n<p>Build for the target platform, or for both with a manifest list:</p>\n<pre><code class=\"language-bash\">docker buildx build --platform linux/amd64,linux/arm64 -t registry.example.test/shop:1.0.0 --push .</code></pre>\n<p>Pipelines that build on amd64 CI runners and are used on arm64 laptops need the multi-platform form. The CI recipe is in <a href=\"/library/docker-build-push-ci-java-images\">building and pushing Docker images in CI</a>.</p>\n<h2>Cause 5: configuration inside the container</h2>\n<p>The application starts, then stops with a Spring failure report, because something the laptop provided is missing in the container: an environment variable, a profile, a file, a database that <code>localhost</code> no longer reaches.</p>\n<pre><code class=\"language-text\">***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nFailed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.</code></pre>\n<p>Inside a container, <code>localhost</code> is the container itself. A database URL pointing at <code>localhost:5432</code> finds nothing. Pass configuration through environment variables (<code>-e SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/shop</code>), use a Compose network so service names resolve, and make sure required secrets are supplied. Read the report with the method in <a href=\"/library/spring-boot-application-failed-start-fix\">fixing Spring Boot application failed to start</a>; the datasource case specifically is in <a href=\"/library/failed-configure-datasource-fix-spring-boot\">Failed to configure a DataSource</a>. Print the environment the container sees: <code>docker run --rm shop:1.0.0 env | sort</code>.</p>\n<h2>Cause 6: the port</h2>\n<p>Two port problems, in opposite directions. The application cannot bind:</p>\n<pre><code class=\"language-text\">Web server failed to start. Port 8080 was already in use.</code></pre>\n<p>Inside a fresh container that means something else in the same container uses 8080 (a second process, an agent), or <code>--network host</code> shares the host's ports. See <a href=\"/library/port-8080-already-use-spring-boot\">port 8080 already in use</a>. More common: the application is running and unreachable, because the port is not published. <code>EXPOSE 8080</code> in the Dockerfile is documentation only. You must map it when you run:</p>\n<pre><code class=\"language-bash\">docker run -d --name shop -p 8080:8080 shop:1.0.0\ncurl -s localhost:8080/actuator/health</code></pre>\n<pre><code class=\"language-text\">{\"status\":\"UP\"}</code></pre>\n<p>Make sure the application listens on all interfaces. A server bound to <code>127.0.0.1</code> inside the container is unreachable from outside it; Spring Boot binds to all by default, but <code>server.address=127.0.0.1</code> from a copied configuration changes that.</p>\n<h2>Cause 7: memory</h2>\n<pre><code class=\"language-bash\">docker inspect shop --format '{{.State.ExitCode}} {{.State.OOMKilled}}'</code></pre>\n<pre><code class=\"language-text\">137 true</code></pre>\n<p>Exit code 137 with <code>OOMKilled: true</code> means the kernel killed the container for exceeding its memory limit, with no Java stack trace. Either the limit is too low for the application (a Spring Boot application with several starters needs roughly 300 to 500 MiB at least), or the heap is sized larger than the limit. With no limit set the JVM sizes itself from the host's memory. Set the limit and let the JVM follow it:</p>\n<pre><code class=\"language-bash\">docker run --memory=768m -e JAVA_TOOL_OPTIONS=\"-XX:MaxRAMPercentage=70\" shop:1.0.0</code></pre>\n<p>If the JVM fails before running at all with <code>Could not reserve enough space for object heap</code>, the requested heap exceeds what is available, per <a href=\"/library/could-not-reserve-enough-space-object\">that error explained</a>. The full diagnosis of a killed container is in <a href=\"/library/java-container-oomkilled-fix-killed-service\">a Java container killed by the OOM killer</a>.</p>\n<h2>Cause 8: permissions and the user</h2>\n<p>An image that runs as a non-root user fails where the application writes: a temp directory, a log file, an upload folder.</p>\n<pre><code class=\"language-text\">java.nio.file.AccessDeniedException: /app/logs/app.log</code></pre>\n<p>or <code>Permission denied</code> on the jar itself if the copy left it unreadable. Check who the process runs as and who owns the files:</p>\n<pre><code class=\"language-bash\">docker run --rm --entrypoint sh shop:1.0.0 -c 'id; ls -ld /app /app/logs /tmp'</code></pre>\n<pre><code class=\"language-text\">uid=10001(app) gid=10001(app)\ndrwxr-xr-x 1 root root 4096 Nov  6 09:30 /app\ndrwxr-xr-x 2 root root 4096 Nov  6 09:30 /app/logs</code></pre>\n<p>The user <code>app</code> cannot write to <code>/app/logs</code>, owned by root. Create writable directories with the right owner in the Dockerfile, or log to stdout instead of a file. Running as non-root is correct; the fix is to own what the process writes, as set out in the non-root user post of this series. A read-only root filesystem needs a mounted writable <code>/tmp</code>.</p>\n<h2>Run a shell to look around</h2>\n<p>When the cause is not clear, replace the entrypoint with a shell and examine the image as the application would see it:</p>\n<pre><code class=\"language-bash\">docker run --rm -it --entrypoint sh shop:1.0.0</code></pre>\n<p>Inside, run the same command by hand and watch it fail:</p>\n<pre><code class=\"language-bash\">java -version\nls -l /app\njava -jar /app/app.jar\nenv | sort | grep -E 'SPRING|JAVA|DB_'</code></pre>\n<p>For a distroless image with no shell, use an image with a shell on the same base for debugging, or <code>docker cp</code> the files out and inspect them. Fix one thing at a time and rebuild; a Dockerfile fix means a new image, and layer caching makes that fast.</p>\n<h2>Where this does not apply</h2>\n<p>If the container runs but the application is unhealthy, you are past starting; read the application log. If the container works under plain Docker and fails in Kubernetes, compare the pod spec (probes, resources, security context, injected environment) with your <code>docker run</code> flags, starting with the crash-loop checklist in <a href=\"/library/java-pod-crashloopbackoff-fix-kubernetes-startup\">diagnosing a Java pod in CrashLoopBackOff</a>. And if the build itself fails, the problem is earlier than the image.</p>","date_published":"2026-11-14T04:04:31+00:00","tags":["DevOps"]},{"id":"https://javahacks.dev/library/port-8080-already-use-spring-boot","url":"https://javahacks.dev/library/port-8080-already-use-spring-boot","title":"Fix Spring Boot Port 8080 Already in Use on Any System","summary":"Find the process holding port 8080 on macOS, Linux and Windows, stop it, or move Spring Boot to another port, and fix the tests that collide.","content_html":"<p>The application stops during startup with a clear message:</p>\n<pre><code class=\"language-text\">Web server failed to start. Port 8080 was already in use.\n\nAction:\n\nIdentify and stop the process that's listening on port 8080 or configure this application to listen on another port.</code></pre>\n<p>Something else is listening on <code>8080</code>. Most of the time that something is the last run of your own application, still alive because the IDE detached it or a terminal tab was closed. This post finds the process on each system and lists the other places a port gets taken. The wider startup checklist is <a href=\"/library/spring-boot-application-failed-start-fix\">application failed to start</a>.</p>\n<h2>Find who owns the port</h2>\n<p>On macOS and Linux:</p>\n<pre><code class=\"language-bash\">lsof -i :8080</code></pre>\n<p>The output lists a command, a PID and the user. On Linux, <code>ss -ltnp 'sport = :8080'</code> gives the same information. Stop the process with <code>kill &lt;pid&gt;</code>, and use <code>kill -9</code> only if a plain <code>kill</code> is ignored, since it skips shutdown hooks.</p>\n<p>On Windows, in Command Prompt:</p>\n<pre><code class=\"language-bash\">netstat -ano | findstr :8080\ntaskkill /PID 12345 /F</code></pre>\n<p>Replace <code>12345</code> with the PID in the last column of the first command.</p>\n<h2>Check Docker before Java</h2>\n<p>A container published with <code>-p 8080:8080</code> holds the host port even though no Java process is visible. List them:</p>\n<pre><code class=\"language-bash\">docker ps --format '{{.Names}}  {{.Ports}}'</code></pre>\n<p>Stop the container or change its published port. On Linux, a rootless Docker or a local reverse proxy can also be the owner, which <code>lsof</code> or <code>ss</code> shows.</p>\n<h2>Cause: your own app, twice</h2>\n<p>IDE run configurations that start a second instance, a <code>spring-boot:run</code> left in a background terminal and DevTools restarts that fail to release the socket all leave a copy behind. If <code>lsof</code> shows <code>java</code> as the command, check the command line with <code>ps -p &lt;pid&gt; -o args=</code> to confirm it is yours before you kill it.</p>\n<h2>Move the port instead</h2>\n<p>When you intend to run two instances, change the port per instance:</p>\n<pre data-filename=\"src/main/resources/application.properties\"><code class=\"language-properties\">server.port=8081</code></pre>\n<p>Or without editing files: <code>./mvnw spring-boot:run -Dspring-boot.run.arguments=--server.port=8081</code>, or <code>SERVER_PORT=8081</code> in the environment. Setting <code>server.port=0</code> asks the operating system for any free port, which is what you want in tests.</p>\n<h2>Tests that collide</h2>\n<p>Two test classes that each start the web server on a fixed port fail intermittently when run in parallel. Use a random port:</p>\n<pre><code class=\"language-java\">@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\nclass OrderApiTest {\n\n    @LocalServerPort int port;\n}</code></pre>\n<p><code>@LocalServerPort</code> injects the port that was chosen. A slice such as <code>@WebMvcTest</code> never opens a port, so prefer it where you can; see <a href=\"/library/java-testing-strategy-practical\">the testing strategy</a>.</p>\n<h2>The exact message, and the line that names the port</h2>\n<p>Spring Boot's failure analyzer replaces a long Tomcat stack trace with a short report. Starting a second instance of the same application on a port that is taken produces this on Spring Boot 4.0.9:</p>\n<pre><code class=\"language-text\">***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nWeb server failed to start. Port 8096 was already in use.\n\nAction:\n\nIdentify and stop the process that's listening on port 8096 or configure this application to listen on another port.</code></pre>\n<p>The port in the message is whichever port was configured, not necessarily 8080; the title of this post uses the default. The report appears when the web server cannot bind, and it means another process holds the socket. The process does not have to be a Java program. Docker containers publishing the port, a database admin tool, a previous run of your own application that did not shut down, and an operating-system service all count.</p>\n<h2>Find the owner on each system</h2>\n<p>The command depends on the platform, and each one prints the process id that owns the listening socket.</p>\n<pre><code class=\"language-bash\"># macOS and Linux\nlsof -nP -iTCP:8080 -sTCP:LISTEN\nss -ltnp 'sport = :8080'          # Linux, shows the process name\n\n# Windows (PowerShell)\nGet-NetTCPConnection -LocalPort 8080 | Select-Object OwningProcess</code></pre>\n<pre><code class=\"language-bash\">docker ps --format '{{.Names}}  {{.Ports}}' | grep 8080</code></pre>\n<p>The Docker command is worth running first on a development machine, because a container with <code>-p 8080:8080</code> holds the port on the host even when nothing visible is running. If the owner is an old copy of your application, stop it with its normal mechanism, not <code>kill -9</code>, so connections drain. If it is another application you need, move yours.</p>\n<h2>Move the port without editing the code</h2>\n<p>Spring Boot reads the port from several places, and the command line wins, so the quickest change touches nothing in the repository.</p>\n<pre><code class=\"language-bash\">java -jar app.jar --server.port=8081\nSERVER_PORT=8081 java -jar app.jar</code></pre>\n<p>In Maven or Gradle development runs, pass it as an argument: <code>./mvnw spring-boot:run -Dspring-boot.run.arguments=--server.port=8081</code>. For a permanent change, set <code>server.port</code> in the configuration for that environment. Use <code>server.port=0</code> to ask the operating system for any free port; the log then prints <code>Tomcat started on port 60054</code>, with the real number.</p>\n<h2>Prevent the collision in tests</h2>\n<p>Tests that start the web server on a fixed port collide with each other when run in parallel and with the application running in the IDE. Use a random port in every test that starts a server.</p>\n<pre><code class=\"language-java\">@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)\nclass OrderApiIT {\n\n    @LocalServerPort int port;\n\n    @Test\n    void healthIsUp() {\n        String body = RestClient.create().get().uri(\"http://localhost:\" + port + \"/actuator/health\")\n                .retrieve().body(String.class);\n        assertThat(body).contains(\"UP\");\n    }\n}</code></pre>\n<p><code>@LocalServerPort</code> injects the port that was chosen. With <code>MOCK</code> environment tests, no port is opened at all, which is the cheapest kind and the right default for controller tests.</p>\n<h2>When the port is free and it still fails</h2>\n<p>If <code>lsof</code> shows nothing and the error persists, three causes remain. A permission problem: ports below 1024 need privileges on Linux, so a service configured for port 80 fails as a normal user with a different message (\"Permission denied\"), and <code>setcap</code> or a reverse proxy is the answer. A bind address conflict: the application is configured to bind to a specific address with <code>server.address</code>, and that address does not exist on the machine, as happens when a configuration for a cloud host is run on a laptop. And a management port that collides: <code>management.server.port</code> set to the same value as <code>server.port</code> or to another taken port reports the same message naming a different number, so read the number in the message instead of assuming it is the main one.</p>\n<h2>Make local ports predictable for a team</h2>\n<p>Port clashes come from several projects using the same default. Agree a port map for the team and write it in the repository: the API on 8080, the admin application on 8081, the mock server on 8082, so that nobody guesses. Put the number in <code>application-local.properties</code> or in the Compose file, and avoid commands that depend on a particular port being free. For services that start many things at once, a Compose file with explicit port mappings documents the choice and lets a developer change one number without editing the code.</p>\n<p>For the cases where a stale process is the cause, add a helper to the README so nobody searches for it each time: a one-line command that prints the owner of the port and, only on request, stops it. Keep the stop step manual, since killing the owner of a port can stop something unrelated.</p>\n<h2>Where this does not apply</h2>\n<p>If the message names a different problem, such as a bind failure on a privileged port below 1024 on Linux, the cause is permissions, not a conflict; run on a high port and map it in the container or proxy. The <a href=\"https://docs.spring.io/spring-boot/reference/web/servlet.html\">Spring Boot web server reference</a> lists the <code>server.*</code> properties, including <code>server.address</code> for binding to a single interface. The project setup this error interrupts is described in <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a>, and a stale container that holds the port is a close relative of <a href=\"/library/spring-boot-docker-image-not-starting\">a Docker image that will not start</a>. The <a href=\"https://docs.spring.io/spring-boot/how-to/index.html\">Spring Boot how-to guides</a> documents the behavior in detail.</p>","date_published":"2026-11-14T04:03:31+00:00","tags":["Spring Boot"]},{"id":"https://javahacks.dev/library/spring-boot-application-failed-start-fix","url":"https://javahacks.dev/library/spring-boot-application-failed-start-fix","title":"Fix Spring Boot Application Failed to Start Errors","summary":"Read the failure analysis Spring Boot prints, classify the cause in a minute and use the condition report when no analyzer matches.","content_html":"<p>The console fills with a stack trace a hundred lines long, ends with <code>Application run failed</code>, and the process exits. The instinct is to scroll to the bottom and search the last line. Don't. For the most common startup failures, Spring Boot has already done the analysis for you, and printed it in a boxed block above the stack trace that most people scroll past: a description of what went wrong and an action to take. When there is no such block, the stack trace has a structure that points to the cause in the last <code>Caused by</code>. This post teaches you to read both, matches the typical failures to their fixes with the exact text, shows how to ask Boot what it decided at startup and gives the habit that keeps a fix from turning into three. Examples use Spring Boot 4 and Java 25.</p>\n<h2>Read the two paragraphs first</h2>\n<p>When Boot recognizes a failure, a <code>FailureAnalyzer</code> replaces the stack trace with a report like this:</p>\n<pre><code class=\"language-text\">***************************\nAPPLICATION FAILED TO START\n***************************\n\nDescription:\n\nWeb server failed to start. Port 8080 was already in use.\n\nAction:\n\nIdentify and stop the process that's listening on port 8080 or configure this application to listen on another port.</code></pre>\n<p>The two paragraphs, <code>Description</code> and <code>Action</code>, are the whole diagnosis. Read them slowly. The description says what failed in plain words; the action says what Boot suggests. This one has a dedicated post, <a href=\"/library/port-8080-already-use-spring-boot\">port 8080 already in use</a>, but note how little guessing was needed. Boot ships dozens of analyzers for common failures, and the list is extended by libraries.</p>\n<p>If you do not see this block, the failure was not recognized, and you read the stack trace instead. Look for the lines beginning <code>Caused by:</code> and read the last one first; it is the root cause. Everything above it is the chain of frames that wrapped the original error as it travelled up.</p>\n<h2>Match the Description to a class</h2>\n<p>The text of the description tells you which kind of failure it is. These are the ones that account for most startup failures.</p>\n<p><strong>A dependency cannot be satisfied.</strong></p>\n<pre><code class=\"language-text\">Description:\n\nParameter 0 of constructor in dev.javahacks.shop.OrderService required a bean of type 'dev.javahacks.shop.PaymentGateway' that could not be found.\n\nAction:\n\nConsider defining a bean of type 'dev.javahacks.shop.PaymentGateway' in your configuration.</code></pre>\n<p>Boot is saying a class has a constructor parameter and no bean of that type exists. Check that the implementing class is annotated, in a scanned package and not excluded by a profile. The detailed checklist is in <a href=\"/library/no-qualifying-bean-type-fix-spring\">No qualifying bean of type</a>.</p>\n<p><strong>Beans form a cycle.</strong></p>\n<pre><code class=\"language-text\">Description:\n\nThe dependencies of some of the beans in the application context form a cycle:\n\n┌─────┐\n|  orderService defined in file [OrderService.class]\n↑     ↓\n|  inventoryService defined in file [InventoryService.class]\n└─────┘</code></pre>\n<p>Two beans each need the other in their constructors, so neither can be built first. Break the cycle in the design, as discussed in <a href=\"/library/circular-dependency-spring-boot-fix-errors\">fixing circular dependencies</a>; <code>spring.main.allow-circular-references=true</code> is a bandage, not a fix.</p>\n<p><strong>No database is configured.</strong></p>\n<pre><code class=\"language-text\">Description:\n\nFailed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.\n\nReason: Failed to determine a suitable driver class</code></pre>\n<p>You have a JDBC starter on the classpath and no connection URL. Set <code>spring.datasource.url</code>, or remove the starter if you do not use a database. The full list of causes is in <a href=\"/library/failed-configure-datasource-fix-spring-boot\">Failed to configure a DataSource</a>.</p>\n<p><strong>A placeholder is unresolved.</strong> The message <code>Could not resolve placeholder 'app.api-key' in value \"${app.api-key}\"</code> means a <code>${...}</code> reference has no value in any property source; see <a href=\"/library/could-not-resolve-placeholder-fix-spring\">Could not resolve placeholder</a>.</p>\n<p><strong>A bean could not be created.</strong> A <code>BeanCreationException</code> is a wrapper: it says that building bean X failed, and the real reason is in its cause. The reading method is in <a href=\"/library/beancreationexception-error-creating-bean-fix-name\">BeanCreationException and its root cause</a>.</p>\n<p><strong>Java version mismatch.</strong> <code>UnsupportedClassVersionError: ... has been compiled by a more recent version of the Java Runtime (class file version 69.0)</code> means the build used a newer JDK than the one running it; see <a href=\"/library/unsupportedclassversionerror-fix-class-file-version-mismatch\">UnsupportedClassVersionError</a>.</p>\n<h2>Property binding failures</h2>\n<p>A typed <code>@ConfigurationProperties</code> class that cannot be filled produces one of the most informative reports Boot has, and also one of the most skipped:</p>\n<pre><code class=\"language-text\">Description:\n\nBinding to target [Bindable@5b8a2e4 type = dev.javahacks.config.ShopProperties] failed:\n\n    Property: shop.timeout\n    Value: \"abc\"\n    Origin: class path resource [application.yaml] - 4:12\n    Reason: failed to convert java.lang.String to java.time.Duration\n\nAction:\n\nUpdate your application's configuration</code></pre>\n<p>It names the property, the offending value, the exact file and line of the origin, and why the conversion failed. Open the file at line 4 and fix the value. Validation failures from <code>@Validated</code> properties look similar, with <code>Reason: must not be blank</code>. The same output appears when an environment variable overrides the file with a bad value, and <code>Origin</code> then names the variable, which is the quickest way to find where a surprising value came from; the precedence rules behind that are covered in the configuration precedence post.</p>\n<h2>When there is no friendly report</h2>\n<p>A startup that dies with a raw stack trace has a structure worth learning. A typical shape:</p>\n<pre><code class=\"language-text\">org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderController': Unsatisfied dependency expressed through constructor parameter 0\n\tat ...\nCaused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderService' defined in file [...]: Failed to instantiate\n\tat ...\nCaused by: java.lang.IllegalStateException: STRIPE_KEY is not set\n\tat dev.javahacks.shop.StripeGateway.&lt;init&gt;(StripeGateway.java:14)</code></pre>\n<p>Read it bottom up. The first lines are Spring reporting which bean it was building when the problem surfaced (<code>orderController</code>, because it needs <code>orderService</code>, which needs the gateway). The last <code>Caused by</code> is the cause: a constructor in your own code threw <code>IllegalStateException</code> because an environment variable was missing. The fix is in <code>StripeGateway</code>'s configuration, not in the controller the trace opens with. A habit to build: ignore the outer wrapper exceptions, find the last <code>Caused by</code>, and look for the first stack frame that belongs to your package.</p>\n<p>Two special cases deserve a glance. If the process is gone with no trace, the operating system killed it: in a container, check for <code>OOMKilled</code> and the exit code 137, described in <a href=\"/library/java-container-oomkilled-fix-killed-service\">a Java container killed by the OOM killer</a>. If it starts locally and fails only in Docker, the image or its environment differs; see <a href=\"/library/spring-boot-docker-image-not-starting\">a Spring Boot Docker image that does not start</a>.</p>\n<h2>Ask Spring Boot what it did</h2>\n<p>When the message is not enough, make Boot show its reasoning. Run with <code>--debug</code> to get the auto-configuration condition evaluation report:</p>\n<pre><code class=\"language-bash\">java -jar target/shop.jar --debug 2&gt;&amp;1 | grep -A 12 'Negative matches'</code></pre>\n<pre><code class=\"language-text\">Negative matches:\n-----------------\n   DataSourceAutoConfiguration:\n      Did not match:\n         - @ConditionalOnClass did not find required class 'javax.sql.DataSource'\n\n   RedisAutoConfiguration:\n      Did not match:\n         - @ConditionalOnClass did not find required class 'org.springframework.data.redis.core.RedisOperations'</code></pre>\n<p>The <code>Positive matches</code> section lists what was configured and why; <code>Negative matches</code> lists what was skipped and the condition that failed. If a bean you expected from an auto-configuration is missing, its negative match says which class or property is absent. For a single bean, raise the log level of the factory to see creation in order:</p>\n<pre><code class=\"language-properties\">logging.level.org.springframework.beans.factory.support.DefaultListableBeanFactory=DEBUG</code></pre>\n<p>and if you want the failure analyzers' work visible, <code>logging.level.org.springframework.boot.diagnostics=DEBUG</code>. The conditions themselves are explained in the reference on <a href=\"https://docs.spring.io/spring-boot/reference/using/auto-configuration.html\">auto-configuration</a>, and the project's <a href=\"https://docs.spring.io/spring-boot/how-to/index.html\">how-to index</a> lists fixes for common startup situations.</p>\n<h2>Fix one thing at a time</h2>\n<p>Startup failures stack: fixing the first reveals the second, and changing three things at once leaves you unable to tell which mattered. Work in a loop. Read the description, make one change, start again. Keep the changes small and commit nothing until it boots. If the application worked before, <code>git diff</code> against the last good commit is the shortest path; a failure that appeared after a dependency upgrade often has a migration note in that project's release notes. For a first project built from scratch, the sequence in <a href=\"/library/spring-boot-guide-first-project-production\">Spring Boot from first project to production</a> gives a known-good baseline to compare with.</p>\n<p>A cheap guard against the worst of these is a startup test, which fails the build instead of the deploy:</p>\n<pre><code class=\"language-java\">@SpringBootTest\nclass ApplicationStartsTest {\n\n    @Test\n    void contextLoads() { }\n}</code></pre>\n<p>If <code>contextLoads</code> passes in CI with production-like profile settings, the wiring problems are mostly gone. It cannot catch missing environment variables, so give the test the same required properties the deployment has.</p>\n<h2>Where this does not apply</h2>\n<p>If the application starts but the first request fails, you are past startup; read the request-time exception instead. If the log says <code>Started ShopApplication</code> and the container is then restarted, the failure is in the probes or memory limits, not in Spring. And in a native image, a startup failure may be a missing reflection hint that the JVM build never shows; run the native test suite to find it.</p>","date_published":"2026-11-14T04:02:31+00:00","tags":["Spring Boot"]},{"id":"https://javahacks.dev/library/debug-production-java-logs-issue-only","url":"https://javahacks.dev/library/debug-production-java-logs-issue-only","title":"How to Debug a Production Issue With Only Logs and Metrics","summary":"Debug a production Java problem without a debugger: build a timeline from logs, follow one request with a correlation id and raise log levels safely.","content_html":"<p>You cannot attach a debugger to production, and the bug exists only there. What you have is logs, metrics and a shell. Used with discipline they are enough for most problems. This post is a procedure for that situation, with the logging setup that makes it work. For the commands that inspect a running JVM safely see <a href=\"/library/jcmd-jstack-jmap-use-safely-production\">jcmd, jstack and jmap</a>, and to read errors in the logs <a href=\"/library/read-java-stack-trace-correctly\">how to read a stack trace</a>.</p>\n<h2>Step 1: define the symptom and the time</h2>\n<p>Write down what is wrong, for whom and since when: \"about 2 percent of checkout requests return 500 since 14:20 UTC\". Then ask what changed near that time: a deployment, a configuration change, a traffic spike, a dependency's incident, a certificate expiry, a database failover, a scheduled job. Most production incidents correlate with a change. Metrics (error rate, latency percentiles, pool usage, GC, CPU) show when and how the curve moved. If the change was a deployment, the diff is a short list of suspects.</p>\n<h2>Step 2: narrow with the logs</h2>\n<p>Search for the error at the time of the first occurrence. Count by type:</p>\n<pre><code class=\"language-bash\">grep \"ERROR\" app.log | sed -E 's/[0-9a-f-]{36}/&lt;id&gt;/g' | cut -c1-160 | sort | uniq -c | sort -rn | head</code></pre>\n<p>This groups repeated errors after replacing identifiers. The most frequent distinct message is usually the symptom; the earliest is often the cause. In a log platform, do the same with a query on the error class and group by time.</p>\n<h2>Step 3: follow one request</h2>\n<p>Logs from many threads interleave, so give each request an id and put it in every line. With SLF4J's MDC:</p>\n<pre><code class=\"language-java\">@Component\nclass CorrelationFilter extends OncePerRequestFilter {\n\n    @Override\n    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)\n            throws ServletException, IOException {\n        String id = Optional.ofNullable(request.getHeader(\"X-Request-Id\")).orElse(UUID.randomUUID().toString());\n        MDC.put(\"requestId\", id);\n        response.setHeader(\"X-Request-Id\", id);\n        try {\n            chain.doFilter(request, response);\n        } finally {\n            MDC.remove(\"requestId\");\n        }\n    }\n}</code></pre>\n<p>Configure the log pattern to print <code>%X{requestId}</code>, and pass the id to downstream calls in a header so one search finds the whole path across services. Distributed tracing (Micrometer Tracing with OpenTelemetry) does this with structure. With the id of one failing request, read its lines in order: what it asked, what it got, where it stopped.</p>\n<h2>Step 4: raise the level, only where needed</h2>\n<p>A bug may sit in code that logs at <code>DEBUG</code>. Changing the level for one logger at runtime avoids a redeploy. With Spring Boot Actuator's <code>loggers</code> endpoint exposed to administrators:</p>\n<pre><code class=\"language-bash\">curl -X POST localhost:8080/actuator/loggers/dev.javahacks.shop.checkout \\\n  -H 'Content-Type: application/json' -d '{\"configuredLevel\":\"DEBUG\"}'</code></pre>\n<p>Set it back to <code>INFO</code> when done, since debug logging can multiply log volume and cost. Never enable debug for the whole application on a busy service, and never log request bodies, tokens or personal data while investigating; logs outlive incidents.</p>\n<h2>Step 5: structured logs</h2>\n<p>Plain text lines are hard to filter. Spring Boot 3.4 and later can write structured JSON logs through properties (<code>logging.structured.format.console=ecs</code>), and Logback encoders do the same on earlier versions. Fields like <code>requestId</code>, <code>userId</code>, <code>orderId</code> and <code>durationMs</code> become filterable and aggregatable. Log events with the identifiers needed to find the entity, not entire payloads.</p>\n<h2>Step 6: inspect the running process, carefully</h2>\n<p>If logs are not enough, a thread dump shows where threads are stuck, and a heap histogram or a JFR recording shows memory and CPU. These tools attach without stopping the service when used correctly. Keep in mind the cost of a heap dump.</p>\n<h2>Step 7: form a hypothesis, test it, write the test</h2>\n<p>A hypothesis names a cause and a prediction: \"the pool is exhausted, so a thread dump will show threads waiting in <code>getConnection</code>\". Check the prediction. When you find the input that fails, reproduce it in a test locally, as in <a href=\"/library/java-testing-strategy-practical\">a practical testing strategy</a>, so the fix is proven and cannot regress. Add the log line or metric that would have shown the problem sooner.</p>\n<h2>What to avoid</h2>\n<ul><li>Changing several things at once, so you cannot tell what worked.</li><li>Restarting before capturing a thread dump or logs; a restart erases evidence.</li><li>Fixing the symptom (raise the timeout) without finding the cause.</li><li>Printing secrets to logs.</li></ul>\n<h2>Metrics first, then logs</h2>\n<p>Logs tell you what happened to one request. Metrics tell you which requests to read. Start with the rate, error and duration numbers per endpoint, because they point at the right log lines. If you export Micrometer timers, a query for the failing endpoint answers three questions at once: did the error rate really rise, when exactly, and did latency move with it:</p>\n<pre><code class=\"language-text\">sum(rate(http_server_requests_seconds_count{uri=\"/checkout\",status=~\"5..\"}[5m]))\n  / sum(rate(http_server_requests_seconds_count{uri=\"/checkout\"}[5m]))\n\nhistogram_quantile(0.99,\n  sum by (le) (rate(http_server_requests_seconds_bucket{uri=\"/checkout\"}[5m])))</code></pre>\n<p>If errors rose but latency did not, the failure is quick, which points at validation, authorization or a dependency that refuses immediately. If latency rose first and errors followed, something is slow and callers are timing out, which points at the pool, a downstream service or a lock. That single distinction removes half the hypotheses before you open a log file.</p>\n<h2>Add the metric you wish you had</h2>\n<p>When the existing metrics cannot answer the question, add one, deploy it and wait for the next occurrence. A timer around the suspicious call costs a few lines:</p>\n<pre><code class=\"language-java\">@Service\nclass PaymentGatewayClient {\n\n    private final Timer chargeTimer;\n    private final Counter chargeFailures;\n\n    PaymentGatewayClient(MeterRegistry registry) {\n        this.chargeTimer = Timer.builder(\"payment.charge\")\n            .publishPercentileHistogram()\n            .register(registry);\n        this.chargeFailures = Counter.builder(\"payment.charge.failures\")\n            .tag(\"reason\", \"timeout\")\n            .register(registry);\n    }\n\n    Receipt charge(ChargeRequest request) {\n        return chargeTimer.record(() -&gt; {\n            try {\n                return gateway.charge(request);\n            } catch (SocketTimeoutException e) {\n                chargeFailures.increment();\n                throw new PaymentUnavailable(e);\n            }\n        });\n    }\n}</code></pre>\n<p>Keep tag values bounded: a user id or an order id as a tag creates a new time series per value and can overload the metrics backend. Put identifiers in logs, and categories in metrics.</p>\n<h2>Querying structured logs</h2>\n<p>With JSON logs, a few <code>jq</code> commands replace the grep and sed pipeline from step two. Pull the failing requests for the time window, group them by the exception class and look at one full example:</p>\n<pre><code class=\"language-bash\">jq -r 'select(.level==\"ERROR\") | .[\"error.type\"] // .message' app.json.log \\\n  | cut -c1-120 | sort | uniq -c | sort -rn | head\n\njq -c 'select(.requestId==\"9f1c2a74\") | {ts: .[\"@timestamp\"], level, logger: .logger_name, message}' app.json.log</code></pre>\n<p>The second command reconstructs the life of one request, in order. Read it with the question \"what did this request expect, and what did it get instead\". Frequently the answer is visible two or three lines before the error: a retry, a timeout of a dependency, a fallback that returned an empty list.</p>\n<h2>Capturing evidence before you restart</h2>\n<p>A restart is the most common cure and the most common destroyer of evidence. Make a habit of collecting four things from the instance first, which together take less than a minute:</p>\n<pre><code class=\"language-bash\">POD=orders-7d9f6b-x2k4q\nkubectl logs $POD --since=30m &gt; $POD.log\nkubectl exec $POD -- jcmd 1 Thread.print &gt; $POD.threads.txt\nkubectl exec $POD -- jcmd 1 GC.heap_info &gt; $POD.heap.txt\nkubectl exec $POD -- jcmd 1 JFR.dump name=1 filename=/tmp/incident.jfr</code></pre>\n<p>Take two thread dumps ten seconds apart, because one dump shows where threads are, and two show whether they are moving. Threads parked in the same <code>getConnection</code> frame in both are evidence of pool exhaustion. Threads in different places are evidence of normal work, and the problem is elsewhere. <code>JFR.dump</code> only works if a recording was already started, so enabling continuous recording at deployment time is the preparation that pays off now.</p>\n<h2>A runbook for the next time</h2>\n<p>The first time an incident costs hours, the second should cost minutes. Write the investigation into a runbook in the repository, next to the code, with the commands that worked:</p>\n<pre><code class=\"language-markdown\">## Checkout 5xx rising\n\n1. Error rate and p99 for /checkout, 5-minute window (dashboard: Checkout / Overview)\n2. Recent deploys and config changes (link to the deploy log)\n3. Top error types: `jq` query above, last 30 minutes\n4. Pool and dependency health: `hikaricp_connections_pending`, `payment_charge_seconds`\n5. Capture threads twice, 10 seconds apart, before any restart\n6. Mitigations: roll back the last deploy; raise payment timeout to 5 s via config; disable promo pricing flag</code></pre>\n<p>Update it after each incident with what was missing. The runbook is also the place to record the decisions that were hard to make under pressure, such as who can authorize a rollback, so that nobody has to invent the rule during an outage.</p>\n<h2>Where this does not apply</h2>\n<p>If you can reproduce the problem in a staging environment with a debugger, do that instead. Incidents with data loss or security impact follow an incident process first. The <a href=\"https://docs.spring.io/spring-boot/reference/features/logging.html\">Spring Boot logging reference</a> and the <a href=\"https://docs.spring.io/spring-boot/api/rest/actuator/loggers.html\">Actuator loggers endpoint documentation</a> are the primary sources.</p>","date_published":"2026-11-14T04:01:31+00:00","tags":["Debugging"]},{"id":"https://javahacks.dev/library/spring-security-lambda-dsl-configuration-explained","url":"https://javahacks.dev/library/spring-security-lambda-dsl-configuration-explained","title":"Spring Security Lambda DSL Configuration Explained","summary":"Spring Security lambda DSL explained: why and() chaining was replaced, how to write authorizeHttpRequests, formLogin and csrf with lambdas.","content_html":"<p>Open a Spring Security configuration written in 2019 and the first thing you notice is a staircase of <code>and()</code> calls. Open one written for Spring Security 7 and the staircase is gone, because the method that made it possible was removed. This post explains why the lambda DSL replaced the chain, how to read it, and how to convert an old class without changing what it allows. Examples target Spring Security 7 with Spring Boot 4 on Java 25.</p>\n<h2>Why the chain had to go</h2>\n<p>The old style was one long fluent call. Every feature method returned a configurer, and <code>and()</code> climbed back up to <code>HttpSecurity</code> so you could start the next feature.</p>\n<pre><code class=\"language-java\">http\n    .authorizeRequests()\n        .antMatchers(\"/public/**\").permitAll()\n        .anyRequest().authenticated()\n        .and()\n    .formLogin()\n        .loginPage(\"/login\")\n        .and()\n    .csrf().disable();</code></pre>\n<p>Nothing in that code stops you from putting a call under the wrong parent. Indentation was a convention, not a rule, and the compiler could not tell <code>.loginPage(\"/login\")</code> on the form login apart from one meant for the logout configurer. Reviewers had to count <code>and()</code> calls in their heads. In a file with eight features, that is where mistakes lived.</p>\n<p>The lambda DSL fixes this by making scope a language construct. Each feature method takes a <code>Customizer&lt;T&gt;</code>, and whatever you do inside the lambda can only touch that feature.</p>\n<h2>The same rules in lambda form</h2>\n<pre><code class=\"language-java\">@Configuration\n@EnableWebSecurity\nclass WebSecurityConfig {\n\n    @Bean\n    SecurityFilterChain web(HttpSecurity http) throws Exception {\n        http\n            .authorizeHttpRequests(auth -&gt; auth\n                .requestMatchers(\"/public/**\").permitAll()\n                .anyRequest().authenticated())\n            .formLogin(form -&gt; form\n                .loginPage(\"/login\")\n                .permitAll())\n            .logout(logout -&gt; logout\n                .logoutSuccessUrl(\"/\"))\n            .csrf(Customizer.withDefaults());\n        return http.build();\n    }\n}</code></pre>\n<p><code>Customizer&lt;T&gt;</code> is a functional interface from <code>T</code> to <code>void</code>. That is all the magic there is. The parameter in <code>form -&gt; form.loginPage(\"/login\")</code> is the form login configurer, and nothing outside the lambda can see it. A misplaced setting is now a compile error or a visible nesting problem, not a silent attachment to the wrong feature.</p>\n<p>The chain between features still exists, but it is the plain return value of <code>http.formLogin(...)</code>, which is <code>HttpSecurity</code> again. Nothing is climbing a tree.</p>\n<h2>Defaults and switching things off</h2>\n<p>Most features work with no settings at all. <code>Customizer.withDefaults()</code> is the lambda that does nothing, and it turns the feature on:</p>\n<pre><code class=\"language-java\">http.httpBasic(Customizer.withDefaults())\n    .oauth2ResourceServer(o -&gt; o.jwt(Customizer.withDefaults()));</code></pre>\n<p>Turning a feature off has two spellings:</p>\n<pre><code class=\"language-java\">http.csrf(csrf -&gt; csrf.disable());\nhttp.csrf(AbstractHttpConfigurer::disable);</code></pre>\n<p>They behave identically. Use the method reference when the lambda would only call <code>disable()</code>. Disable CSRF protection only for APIs that are stateless and authenticate with a header token, because a browser that sends cookies automatically is exactly what CSRF protection exists for. The reasoning is in <a href=\"/library/prevent-csrf-java-spring-jakarta-apps\">preventing CSRF</a>.</p>\n<h2>What else changed with the method names</h2>\n<p>The lambda DSL arrived alongside several renames. Old code usually needs all of them at once, so it helps to see them together.</p>\n<table><thead><tr><th>Old</th><th>Current</th></tr></thead><tbody><tr><td><code>authorizeRequests()</code></td><td><code>authorizeHttpRequests(...)</code></td></tr><tr><td><code>antMatchers</code>, <code>mvcMatchers</code>, <code>regexMatchers</code></td><td><code>requestMatchers</code></td></tr><tr><td><code>.and()</code></td><td>removed, nest instead</td></tr><tr><td><code>extends WebSecurityConfigurerAdapter</code></td><td>a <code>SecurityFilterChain</code> bean</td></tr></tbody></table>\n<p>The last row is a separate migration with its own traps, covered in <a href=\"/library/websecurityconfigureradapter-migration-migrate-security-beans\">migrating WebSecurityConfigurerAdapter</a> and <a href=\"/library/securityfilterchain-configure-spring-security\">configuring a SecurityFilterChain</a>. The release notes for the version that removed <code>and()</code> are summarized in <a href=\"/library/spring-security-7-changed\">what changed in Spring Security 7</a>.</p>\n<p>One behavior difference deserves a flag. <code>authorizeHttpRequests</code> evaluates rules in the order you write them and stops at the first match, and so did <code>authorizeRequests</code>. But the new method authorizes every dispatch type by default, including forwards and error dispatches, where the old one did not. If an old application relied on error pages being open without a rule, add <code>.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()</code> ahead of the catch-all.</p>\n<h2>Several chains in one application</h2>\n<p>A real application often has two security stories: a stateless API and a browser site. Define one chain for each and let <code>securityMatcher</code> decide which requests a chain owns.</p>\n<pre><code class=\"language-java\">@Bean\n@Order(1)\nSecurityFilterChain api(HttpSecurity http) throws Exception {\n    http.securityMatcher(\"/api/**\")\n        .authorizeHttpRequests(a -&gt; a.anyRequest().hasAuthority(\"SCOPE_api\"))\n        .oauth2ResourceServer(o -&gt; o.jwt(Customizer.withDefaults()))\n        .sessionManagement(s -&gt; s\n            .sessionCreationPolicy(SessionCreationPolicy.STATELESS));\n    return http.build();\n}\n\n@Bean\n@Order(2)\nSecurityFilterChain site(HttpSecurity http) throws Exception {\n    http.authorizeHttpRequests(a -&gt; a.anyRequest().authenticated())\n        .formLogin(Customizer.withDefaults());\n    return http.build();\n}</code></pre>\n<p>The lowest <code>@Order</code> that matches wins, and a chain with no <code>securityMatcher</code> matches everything. Put the specific chain first and the catch-all last. If the catch-all comes first, the API chain is dead code and nothing warns you.</p>\n<h2>A migration that does not change behavior</h2>\n<p>Treat the conversion as a refactoring with a safety net, not a rewrite.</p>\n<ol><li>Write tests for the access rules first. A <code>@WebMvcTest</code> with <code>@WithMockUser</code> and one request per rule is enough to pin down what the current configuration allows.</li><li>Replace <code>authorizeRequests()</code> with <code>authorizeHttpRequests(...)</code> and move the rules inside a lambda.</li><li>Turn each <code>.feature().a().b().and()</code> into <code>.feature(f -&gt; f.a().b())</code>. Do it one feature at a time and compile between each.</li><li>Swap the matcher methods for <code>requestMatchers</code>. On Spring MVC applications this picks the right matcher for each path, so check any path with a servlet prefix.</li><li>Delete leftover <code>and()</code> calls. The compiler finds them for you in Spring Security 7.</li><li>Run the tests again. A rule that used to pass by accident now fails loudly, and that is the point.</li></ol>\n<p>The common surprise in step 4 is an <code>antMatchers(\"/admin\")</code> that used to match <code>/admin/</code> with a trailing slash. Since Spring Framework 6, trailing slash matching is off by default, so <code>/admin/</code> no longer matches <code>/admin</code>. Add the second pattern if you still need it.</p>\n<h2>Keeping the bean readable</h2>\n<p>A configuration with ten features still fits on one screen if each nested lambda is short. When a block grows, extract it:</p>\n<pre><code class=\"language-java\">private static void rules(AuthorizeHttpRequestsConfigurer&lt;HttpSecurity&gt;\n        .AuthorizationManagerRequestMatcherRegistry auth) {\n    auth.requestMatchers(\"/public/**\").permitAll()\n        .requestMatchers(\"/admin/**\").hasRole(\"ADMIN\")\n        .anyRequest().authenticated();\n}</code></pre>\n<p>Then call <code>http.authorizeHttpRequests(WebSecurityConfig::rules)</code>. The method reference works because the lambda is a <code>Customizer</code>. It reads better than a 30 line lambda, and the long generic type is a good reason to leave short rules inline.</p>\n<h2>Test the chain you configured</h2>\n<p>A security configuration without a test is a configuration you only trust until the next refactoring. A web slice that imports the configuration checks the rules as a client sees them, including the ones you meant to be closed:</p>\n<pre><code class=\"language-java\">@WebMvcTest(OrderController.class)\n@Import(SecurityConfig.class)\nclass SecurityRulesTest {\n\n    @Autowired MockMvc mvc;\n    @MockitoBean OrderService orders;\n\n    @Test\n    void anonymousIsRejected() throws Exception {\n        mvc.perform(get(\"/api/orders\")).andExpect(status().isUnauthorized());\n    }\n\n    @Test\n    void tokenWithReadScopeCanList() throws Exception {\n        mvc.perform(get(\"/api/orders\").with(jwt().authorities(new SimpleGrantedAuthority(\"SCOPE_orders:read\"))))\n           .andExpect(status().isOk());\n    }\n\n    @Test\n    void tokenWithReadScopeCannotWrite() throws Exception {\n        mvc.perform(post(\"/api/orders\").with(jwt().authorities(new SimpleGrantedAuthority(\"SCOPE_orders:read\")))\n                .contentType(MediaType.APPLICATION_JSON).content(\"{}\"))\n           .andExpect(status().isForbidden());\n    }\n}</code></pre>\n<p>The three tests pin the shape of the rules: no credentials gives <code>401</code>, enough authority gives <code>200</code>, and valid credentials without the right authority give <code>403</code>. When you migrate from the chained style to the lambda form, run these tests before and after, and the migration is proven not to have changed behavior. To see why a request was treated as it was, set <code>logging.level.org.springframework.security=DEBUG</code> and read the list of filters the request passed through, since the filter that rejected it is named in the log.</p>\n<h2>Where this stops mattering</h2>\n<p>Applications that act only as an OAuth 2 resource server can configure much of this through properties such as <code>spring.security.oauth2.resourceserver.jwt.issuer-uri</code> and never write a chain at all. Boot's auto-configuration builds the chain from them, and the DSL only matters once you need to deviate. The reference for every feature method is the <a href=\"https://docs.spring.io/spring-security/reference/servlet/configuration/java.html\">Spring Security Java configuration</a> chapter, and the <a href=\"https://docs.spring.io/spring-security/reference/api/java/org/springframework/security/config/Customizer.html\">Customizer Javadoc</a> is short enough to read in full.</p>","date_published":"2026-11-14T04:00:31+00:00","tags":["Security"]},{"id":"https://javahacks.dev/library/hikaricp-pool-size-sizing-formula-common","url":"https://javahacks.dev/library/hikaricp-pool-size-sizing-formula-common","title":"HikariCP Pool Size Formula and Common Mistakes to Avoid","summary":"Size a HikariCP pool using the cores and spindles formula, Little's Law and measurement, and avoid the common mistakes of oversized pools.","content_html":"<p>The instinct is \"more connections, more throughput\". For a database it is usually the reverse: beyond a point, more connections make everything slower.</p>\n<h2>Why small pools work</h2>\n<p>A database server runs queries on its cores and reads from its storage. If the server has 8 cores and is already busy, 200 concurrent queries do not run faster, they take turns, with context switching, lock contention and cache thrash on top. A smaller pool lets the database finish each query sooner and moves the waiting to the application, where waiting is cheap.</p>\n<p>A widely quoted starting rule, from the HikariCP project's \"About Pool Sizing\" page and the PostgreSQL wiki, is:</p>\n<pre><code class=\"language-text\">connections = (core_count * 2) + effective_spindle_count</code></pre>\n<p>For an 8-core database server with an SSD, that gives about 17. Treat it as a starting point for the database host, not a law, and keep the whole fleet in mind.</p>\n<h2>Little's Law as a check</h2>\n<p>The number of connections in use on average is the arrival rate times the time each request holds a connection:</p>\n<pre><code class=\"language-text\">connections_in_use = requests_per_second * seconds_holding_a_connection</code></pre>\n<p>A service handling 400 requests per second where each request holds a connection for 20 ms needs 400 * 0.02 = 8 connections on average. Add headroom for bursts: 12 to 16. If the same endpoint held the connection for 200 ms (a slow query, or a transaction that also calls an HTTP service), it would need 80, and the better fix is to cut the hold time. The effect of what you do inside a transaction is why <a href=\"/library/jdbc-transactions-manage-manually\">keeping transactions short</a> beats growing the pool.</p>\n<h2>The fleet limit</h2>\n<p>Each application instance has its own pool, so 20 instances of a service with pool size 20 open 400 connections. PostgreSQL's default <code>max_connections</code> is 100, and each connection costs memory (several megabytes). Compute:</p>\n<pre><code class=\"language-text\">instances * maximumPoolSize + other clients + admin headroom &lt;= max_connections</code></pre>\n<p>When autoscaling adds instances, the total grows. Use a pooler such as PgBouncer in front of PostgreSQL, or set a smaller pool per instance.</p>\n<h2>Common mistakes</h2>\n<ol><li><strong>Setting the pool to the thread count.</strong> A Tomcat with 200 threads does not need 200 connections. Most threads do not hold one at any moment.</li><li><strong>Raising the pool to fix timeouts.</strong> A <a href=\"/library/connection-not-available-request-timed-out\">connection timeout</a> usually means connections are held too long or leaked, and a larger pool only delays the symptom.</li><li><strong>Different values for minimum and maximum.</strong> HikariCP's author recommends a fixed-size pool for steady load: <code>minimumIdle</code> equal to <code>maximumPoolSize</code>.</li><li><strong>Ignoring other consumers.</strong> Batch jobs, migrations and admin tools use connections too.</li><li><strong>Copying a number from another system.</strong> The right size depends on your queries and hardware.</li><li><strong>Holding a connection during remote calls.</strong> An open transaction during a call to a payment gateway ties up a connection for seconds.</li></ol>\n<h2>Measure to confirm</h2>\n<p>Run a load test at the expected traffic with different sizes (5, 10, 20, 40). Record throughput, latency percentiles, the Micrometer metrics <code>hikaricp.connections.pending</code> and <code>hikaricp.connections.usage</code>, and database CPU and active sessions. The best size is the smallest one after which throughput stops improving and pending connections stay near zero.</p>\n<h2>With virtual threads</h2>\n<p>Virtual threads make it easy to start thousands of concurrent requests, and the pool becomes the throttle. The queue inside the pool is cheap, and the <code>connectionTimeout</code> decides how long a request waits. Do not raise the pool to match thread counts. Limiting concurrency to the database is the pool's job, and the sizing is the same.</p>\n<h2>A worked sizing, start to finish</h2>\n<p>Take an order service with four instances behind a load balancer, talking to one PostgreSQL primary with 8 cores. Peak traffic is 600 requests per second across the fleet, so 150 per instance. A trace of the busiest endpoint shows 18 ms of connection hold time on average, with a tail at 60 ms.</p>\n<pre><code class=\"language-text\">per instance: 150 req/s * 0.018 s = 2.7 connections in use on average\ntail case:    150 req/s * 0.060 s = 9.0 connections</code></pre>\n<p>A pool of 10 per instance covers the tail, and the fleet total is 40. That is well under the formula's 17 for the database host if you count only what runs at once, because most requests are not in a query at the same instant, and well under PostgreSQL's default <code>max_connections</code> of 100. If the autoscaler can go to 12 instances, the total becomes 120 and the default limit is gone. That is the number to plan around, not the steady-state count.</p>\n<h2>The configuration that follows from it</h2>\n<p>Spring Boot reads the HikariCP settings from <code>spring.datasource.hikari.*</code>:</p>\n<pre><code class=\"language-yaml\">spring:\n  datasource:\n    url: jdbc:postgresql://db:5432/orders\n    hikari:\n      maximum-pool-size: 10\n      minimum-idle: 10\n      connection-timeout: 2000\n      max-lifetime: 1500000\n      leak-detection-threshold: 10000\n      pool-name: orders-pool</code></pre>\n<p>Each value has a reason. <code>maximum-pool-size</code> and <code>minimum-idle</code> are equal, so the pool never resizes under load. <code>connection-timeout</code> is 2000 ms rather than the 30,000 ms default, because a request that waited 30 seconds for a connection has already failed from the caller's point of view, and a fast error is easier to see and to retry. <code>max-lifetime</code> stays a few minutes below any limit the database or a proxy imposes on connection age, so the pool retires connections before something kills them mid-query. <code>leak-detection-threshold</code> logs a stack trace when a connection is held for more than 10 seconds, which finds the code that forgot to close one.</p>\n<h2>Watching the pool while it runs</h2>\n<p>Sizing from a formula is a first guess, and the metrics are the correction. Spring Boot registers the Hikari metrics with Micrometer when Actuator is present. You can read the three that matter without any dashboard:</p>\n<pre><code class=\"language-java\">@Component\nclass PoolReport {\n\n    private final MeterRegistry registry;\n\n    PoolReport(MeterRegistry registry) {\n        this.registry = registry;\n    }\n\n    @Scheduled(fixedRate = 30_000)\n    void log() {\n        double active = registry.get(\"hikaricp.connections.active\").gauge().value();\n        double pending = registry.get(\"hikaricp.connections.pending\").gauge().value();\n        double max = registry.get(\"hikaricp.connections.max\").gauge().value();\n        System.out.printf(\"pool active=%.0f pending=%.0f max=%.0f%n\", active, pending, max);\n    }\n}</code></pre>\n<p>Read the numbers this way. If <code>pending</code> is regularly above zero while the database CPU is idle, the pool is too small for the hold time, and you either grow it a little or shorten transactions. If <code>pending</code> is above zero and the database is saturated, a bigger pool will make it worse. If <code>active</code> sits at the maximum and <code>pending</code> is zero, you are right at the edge and a burst will start queueing. The <code>hikaricp.connections.acquire</code> timer shows how long callers wait, and its high percentile is the number your users feel.</p>\n<h2>A transaction that costs five pool slots</h2>\n<p>The hold time is the lever you control, and the most common way to inflate it is a remote call inside a transaction:</p>\n<pre><code class=\"language-java\">@Transactional\npublic void checkout(long orderId) {\n    Order order = orders.findById(orderId).orElseThrow();\n    PaymentResult result = paymentClient.charge(order.total());   // 400 ms over HTTP\n    order.markPaid(result.reference());\n}</code></pre>\n<p>The connection is checked out when the transaction starts and returned when the method ends, so it is held for the 400 ms the payment gateway takes. At 100 checkouts per second that is 40 connections doing nothing. Splitting the method so the charge happens outside the transaction brings the hold back to a few milliseconds:</p>\n<pre><code class=\"language-java\">public void checkout(long orderId) {\n    Order order = loader.load(orderId);                 // short transaction\n    PaymentResult result = paymentClient.charge(order.total());   // no connection held\n    marker.markPaid(orderId, result.reference());      // short transaction\n}</code></pre>\n<p>This trade has a cost: the charge and the update are no longer atomic, so you need an idempotency key on the charge and a way to recover an order that was charged but not marked. That is the usual price of not holding a connection across a network call, and it is better paid in design than in outages.</p>\n<h2>Where this does not apply</h2>\n<p>Read replicas, sharded databases and analytics warehouses have different limits, and each pool should be sized for its target. The configuration reference is <a href=\"/library/hikaricp-use-connection-pools\">the HikariCP guide</a>, and thread-pool sizing logic is related in <a href=\"/library/java-thread-pool-size-cpu-io\">thread pool size</a>. The reference is <a href=\"https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing\">About Pool Sizing</a>, and the <a href=\"https://wiki.postgresql.org/wiki/Number_Of_Database_Connections\">PostgreSQL wiki on connection counts</a> explains the database side.</p>","date_published":"2026-11-14T03:59:31+00:00","tags":["Hibernate"]},{"id":"https://javahacks.dev/library/java-dockerfile-write-right-way","url":"https://javahacks.dev/library/java-dockerfile-write-right-way","title":"How to Write a Dockerfile for Java Apps the Right Way","summary":"Write a Dockerfile for a Java service with a multi-stage build, dependency caching, a non-root user, container-aware memory settings and a health check.","content_html":"<p>A working Dockerfile for a Java service takes five lines. A good one takes about twenty, and each added line answers a failure that someone hit in production: slow builds, jars that never receive <code>SIGTERM</code>, processes killed by memory limits, images that run as root. This post builds the Dockerfile up and explains each decision. The next steps, <a href=\"/library/java-docker-image-small-build-app\">making it small</a> and <a href=\"/library/docker-multi-stage-java-use-builds\">using multi-stage builds</a>, refine it.</p>\n<h2>The result first</h2>\n<pre data-filename=\"Dockerfile\"><code class=\"language-dockerfile\"># syntax=docker/dockerfile:1\nFROM eclipse-temurin:25-jdk AS build\nWORKDIR /workspace\n\nCOPY .mvn/ .mvn/\nCOPY mvnw pom.xml ./\nRUN ./mvnw -q dependency:go-offline\n\nCOPY src/ src/\nRUN ./mvnw -q -DskipTests package \\\n &amp;&amp; java -Djarmode=tools -jar target/*.jar extract --layers --destination extracted\n\nFROM eclipse-temurin:25-jre\nWORKDIR /app\nRUN useradd --system --uid 10001 app\n\nCOPY --from=build /workspace/extracted/dependencies/ ./\nCOPY --from=build /workspace/extracted/spring-boot-loader/ ./\nCOPY --from=build /workspace/extracted/snapshot-dependencies/ ./\nCOPY --from=build /workspace/extracted/application/ ./\n\nUSER app\nEXPOSE 8080\nENTRYPOINT [\"java\", \"-XX:MaxRAMPercentage=65\", \"-jar\", \"shop.jar\"]</code></pre>\n<p>The jar name after <code>extract</code> follows your artifact, so adjust <code>shop.jar</code>; set <code>&lt;finalName&gt;shop&lt;/finalName&gt;</code> in the POM to make it fixed. If the Spring Boot version you use predates the <code>tools</code> jar mode, the equivalent was <code>-Djarmode=layertools</code> with <code>extract</code>. Check the container images chapter of the reference for your version.</p>\n<h2>Cache the dependencies</h2>\n<pre><code class=\"language-dockerfile\">COPY .mvn/ .mvn/\nCOPY mvnw pom.xml ./\nRUN ./mvnw -q dependency:go-offline\nCOPY src/ src/</code></pre>\n<p>Docker rebuilds a layer when its inputs change, and every later layer too. If you copied <code>src</code> first, any code edit would invalidate the layer that downloads dependencies. With this order, the download runs only when <code>pom.xml</code> changes. In CI use BuildKit cache mounts for even better results: <code>RUN --mount=type=cache,target=/root/.m2 ./mvnw package</code>.</p>\n<h2>Run as a normal user</h2>\n<pre><code class=\"language-dockerfile\">RUN useradd --system --uid 10001 app\nUSER app</code></pre>\n<p>A container process running as root can write anywhere in the container and, with misconfiguration, on the host. A fixed numeric uid works with Kubernetes policies that require a non-root user. Make sure directories the app writes to (logs, <code>/tmp</code>) are writable by it.</p>\n<h2>Start the JVM correctly</h2>\n<p>The exec form (a JSON array) makes <code>java</code> the main process. The shell form (<code>ENTRYPOINT java -jar app.jar</code>) wraps it in <code>sh -c</code>, so <code>SIGTERM</code> goes to the shell, and the JVM may be killed by <code>SIGKILL</code> after the grace period without running shutdown hooks or Spring's graceful shutdown. If you need environment variable expansion in options, use <code>JAVA_TOOL_OPTIONS</code> or write a small entrypoint script that ends with <code>exec java ...</code>.</p>\n<p>Memory:</p>\n<pre><code class=\"language-dockerfile\">ENTRYPOINT [\"java\", \"-XX:MaxRAMPercentage=65\", \"-jar\", \"shop.jar\"]</code></pre>\n<p><code>MaxRAMPercentage</code> follows the container's memory limit, unlike a fixed <code>-Xmx</code>. Leave room for non-heap memory, as explained in <a href=\"/library/jvm-memory-areas-heap-stack-metaspace\">JVM memory areas</a>, and see what happens when it is wrong in <a href=\"/library/java-container-oomkilled-fix-killed-service\">OOMKilled</a>.</p>\n<h2>Pin the base image</h2>\n<p><code>eclipse-temurin:25-jre</code> follows the 25 line and moves with updates. For reproducible builds, pin a digest (<code>eclipse-temurin:25-jre@sha256:...</code>) and update it deliberately with a tool like Dependabot or Renovate. Never use <code>latest</code>.</p>\n<h2>.dockerignore</h2>\n<pre data-filename=\".dockerignore\"><code class=\"language-text\">target/\n.git/\n.idea/\n*.iml\n.env</code></pre>\n<p>Keeping <code>target/</code> and <code>.git/</code> out of the build context speeds the build and prevents local build output and secrets from leaking into layers. A <code>.env</code> file with credentials copied by <code>COPY . .</code> ends up in the image history.</p>\n<h2>Health check</h2>\n<p>For plain Docker (not Kubernetes, which has its own probes), a health check lets the orchestrator know the service works:</p>\n<pre><code class=\"language-dockerfile\">HEALTHCHECK --interval=30s --timeout=3s --start-period=60s \\\n  CMD wget -q --spider http://localhost:8080/actuator/health || exit 1</code></pre>\n<p>Install <code>wget</code> or <code>curl</code> in the image, or skip the instruction and use the platform's probes. Give a generous <code>start-period</code> for the JVM.</p>\n<h2>Secrets</h2>\n<p>Never <code>COPY</code> credentials or pass them as <code>ARG</code> values that stay in the history. Inject them at runtime through environment variables or mounted secrets. BuildKit's <code>--mount=type=secret</code> supplies build-time secrets without leaving them in layers.</p>\n<h2>Common mistakes</h2>\n<ul><li><code>COPY . .</code> before dependency resolution.</li><li>A shell-form <code>ENTRYPOINT</code>.</li><li>A JDK in the final image.</li><li>A fixed <code>-Xmx</code> larger than the container limit (<a href=\"/library/could-not-reserve-enough-space-object\">Could not reserve enough space for object heap</a>).</li><li>Building the jar on the host and copying it, so CI and laptops produce different images.</li></ul>\n<h2>An entrypoint script for the cases the exec form cannot cover</h2>\n<p>The exec form is right until you need to compute something at startup: a heap size from a variable, an extra flag in one environment, a file that must exist. Put that logic in a small script and finish it with <code>exec</code>, so the JVM replaces the shell and still receives signals:</p>\n<pre><code class=\"language-bash\">#!/bin/sh\nset -eu\n\nJAVA_OPTS=\"${JAVA_OPTS:--XX:MaxRAMPercentage=65}\"\n\nif [ -n \"${DB_PASSWORD_FILE:-}\" ]; then\n  export SPRING_DATASOURCE_PASSWORD=\"$(cat \"$DB_PASSWORD_FILE\")\"\nfi\n\nexec java $JAVA_OPTS -jar /app/shop.jar \"$@\"</code></pre>\n<pre><code class=\"language-dockerfile\">COPY --chmod=0755 entrypoint.sh /app/entrypoint.sh\nENTRYPOINT [\"/app/entrypoint.sh\"]</code></pre>\n<p>Without the <code>exec</code>, the shell stays as process 1 and the JVM is its child, which is exactly the signal problem the exec form avoids. The <code>$JAVA_OPTS</code> expansion is unquoted on purpose so that several flags split into separate arguments, and that is also why a value containing spaces needs care. Reading a secret from a mounted file keeps it out of the image and out of <code>docker inspect</code> output.</p>\n<h2>Let the application shut down gracefully</h2>\n<p><code>SIGTERM</code> reaching the JVM is half of a clean stop. The other half is that the application drains in-flight requests before it exits, and Spring Boot does that when you ask:</p>\n<pre><code class=\"language-yaml\">server:\n  shutdown: graceful\nspring:\n  lifecycle:\n    timeout-per-shutdown-phase: 25s</code></pre>\n<p>The container runtime then has to wait at least that long. Docker's default is 10 seconds before <code>SIGKILL</code>, so give it room, and make the Kubernetes <code>terminationGracePeriodSeconds</code> a few seconds larger than the phase timeout:</p>\n<pre><code class=\"language-bash\">docker run --name shop --stop-timeout 30 -p 8080:8080 shop:1.0\ndocker stop shop</code></pre>\n<h2>Verify the image instead of trusting it</h2>\n<p>Four checks take under a minute, and each catches one of the mistakes above:</p>\n<pre><code class=\"language-bash\">docker build -t shop:1.0 .\ndocker run -d --name shop --memory 512m -p 8080:8080 shop:1.0\n\ndocker exec shop id\ndocker exec shop sh -c 'ps -o pid,user,args -p 1'\ndocker inspect shop --format '{{.HostConfig.Memory}}'\n\ntime docker stop shop</code></pre>\n<p><code>id</code> should show the numeric user you created and not root. <code>ps</code> should show <code>java</code> as process 1 (or <code>entrypoint.sh</code> only until the <code>exec</code>), and if it shows <code>sh -c java ...</code> you have the shell form. The inspect call confirms the memory limit the JVM will read. And <code>docker stop</code> should return in a second or two, because a stop that takes the full ten seconds means the JVM never saw the signal and was killed.</p>\n<h2>The Gradle variant</h2>\n<p>The same layering idea works with Gradle. Only the wrapper and the dependency step change:</p>\n<pre><code class=\"language-dockerfile\">FROM eclipse-temurin:25-jdk AS build\nWORKDIR /workspace\nCOPY gradlew settings.gradle.kts build.gradle.kts ./\nCOPY gradle/ gradle/\nRUN ./gradlew --no-daemon dependencies &gt; /dev/null\nCOPY src/ src/\nRUN ./gradlew --no-daemon bootJar -x test</code></pre>\n<p>The <code>dependencies</code> task resolves and downloads the dependency graph without compiling anything, so the layer is reused until a build file changes. Skipping tests inside the image build is a choice: run them in CI before the build, so a failed test stops the pipeline early and the image only contains code that passed.</p>\n<h2>A cache mount for repeat builds</h2>\n<p>If the CI runner keeps BuildKit's cache, a cache mount avoids downloading every artifact on every build even when <code>pom.xml</code> changed:</p>\n<pre><code class=\"language-dockerfile\">RUN --mount=type=cache,target=/root/.m2 ./mvnw -q -DskipTests package</code></pre>\n<p>The cache lives outside the image, so it never grows the layers. It is a speed-up and not a correctness feature: a build must still succeed from an empty cache, and a clean build on a fresh runner proves that.</p>\n<h2>Where this does not apply</h2>\n<p>If you use Spring Boot's buildpacks (<code>spring-boot:build-image</code>) or Jib, they produce a similar image without a Dockerfile and apply these practices for you. The <a href=\"https://docs.docker.com/reference/dockerfile/\">Dockerfile reference</a> and the <a href=\"https://docs.spring.io/spring-boot/reference/packaging/container-images/dockerfiles.html\">Spring Boot Dockerfile guide</a> are the primary sources, and the image that will not start is covered in <a href=\"/library/spring-boot-docker-image-not-starting\">troubleshooting a Spring Boot image</a>.</p>","date_published":"2026-11-14T03:58:31+00:00","tags":["DevOps"]}]}