New posts for Spring and Hibernate

This commit is contained in:
2026-11-06 01:05:27 +05:30
parent 51913ad9d4
commit dc13293046
136 changed files with 5268 additions and 0 deletions
@@ -0,0 +1,44 @@
package com.ankurm.runners.args;
import com.ankurm.runners.support.Trace;
import java.util.Arrays;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/** Scenario 4: the same command line, as the two runner flavours see it. */
@SpringBootApplication
public class ArgsApp {
public static void main(String[] args) {
SpringApplication.run(ArgsApp.class, args);
}
@Component
@Order(1)
static class Cli implements CommandLineRunner {
@Override
public void run(String... args) {
Trace.add("CommandLineRunner String[] args = %s", Arrays.toString(args));
}
}
@Component
@Order(2)
static class App implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
Trace.add("ApplicationRunner getSourceArgs() = %s", Arrays.toString(args.getSourceArgs()));
Trace.add("ApplicationRunner getOptionNames() = %s", args.getOptionNames());
Trace.add("ApplicationRunner getOptionValues(name) = %s", args.getOptionValues("name"));
Trace.add("ApplicationRunner getOptionValues(verbose) = %s", args.getOptionValues("verbose"));
Trace.add("ApplicationRunner getOptionValues(missing) = %s", args.getOptionValues("missing"));
Trace.add("ApplicationRunner containsOption(verbose) = %s", args.containsOption("verbose"));
Trace.add("ApplicationRunner getNonOptionArgs() = %s", args.getNonOptionArgs());
}
}
}
@@ -0,0 +1,65 @@
package com.ankurm.runners.blocking;
import com.ankurm.runners.support.Trace;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Scenarios 7 and 8: a web application whose runner takes a long time. With profile {@code blocking} the runner
* waits on a latch in the runner thread; with profile {@code async} it hands the same wait to a virtual thread and
* returns at once. The test opens and closes the latch, so nothing here depends on a sleep.
*/
@SpringBootApplication
public class BlockingApp {
public static void main(String[] args) {
SpringApplication.run(BlockingApp.class, args);
}
@RestController
static class Ping {
@GetMapping("/ping")
String ping() {
return "pong";
}
}
@Bean
@Profile("blocking")
CommandLineRunner blockingRunner() {
return args -> {
Trace.add("runner: started on %s, now waiting (think: warming a cache for 40 s)", Trace.where());
Gate.RUNNER_STARTED.countDown();
Gate.RELEASE.await(30, TimeUnit.SECONDS);
Trace.add("runner: finished, returning to SpringApplication.run");
};
}
@Bean
@Profile("async")
CommandLineRunner asyncRunner() {
return args -> {
Thread.ofVirtual()
.uncaughtExceptionHandler((thread, e) -> {
Trace.add("background work on %s failed: %s", Trace.where(), e.getMessage());
Gate.BACKGROUND_DONE.countDown();
})
.start(() -> {
Gate.RUNNER_STARTED.countDown();
try {
Gate.RELEASE.await(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
throw new IllegalStateException("the warm-up blew up");
});
Trace.add("runner: started the work on a virtual thread and returned");
};
}
}
@@ -0,0 +1,20 @@
package com.ankurm.runners.blocking;
import java.util.concurrent.CountDownLatch;
/** Latches the test uses to freeze and release the slow work, so the scenario needs no sleeps. */
public final class Gate {
public static volatile CountDownLatch RUNNER_STARTED = new CountDownLatch(1);
public static volatile CountDownLatch RELEASE = new CountDownLatch(1);
public static volatile CountDownLatch BACKGROUND_DONE = new CountDownLatch(1);
private Gate() {
}
public static void reset() {
RUNNER_STARTED = new CountDownLatch(1);
RELEASE = new CountDownLatch(1);
BACKGROUND_DONE = new CountDownLatch(1);
}
}
@@ -0,0 +1,164 @@
package com.ankurm.runners.failure;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Scenarios 5 and 6. Run it with {@code --spring.profiles.active=runner-fails}, {@code ready-fails}, {@code exit-code}
* or {@code checked} and look at the exit code and the console.
*/
@SpringBootApplication
public class FailureApp {
public static void main(String[] args) {
SpringApplication.run(FailureApp.class, args);
}
/** Always present: shows which of the startup events fire at all. */
@Component
static class Observer {
private final ApplicationAvailability availability;
Observer(ApplicationAvailability availability) {
this.availability = availability;
}
@EventListener
void started(ApplicationStartedEvent e) {
Trace.add("ApplicationStartedEvent");
}
@EventListener
void ready(ApplicationReadyEvent e) {
Trace.add("ApplicationReadyEvent (observer, readiness: %s)", availability.getReadinessState());
}
@EventListener
void failed(ApplicationFailedEvent e) {
Trace.add("ApplicationFailedEvent: %s", e.getException());
}
@EventListener
void closed(ContextClosedEvent e) {
Trace.add("ContextClosedEvent (the context is shutting down)");
}
}
@RestController
static class Ping {
@GetMapping("/ping")
String ping() {
return "pong";
}
}
// ---- profile runner-fails: the second of three runners throws ----------------------------------------
@Bean
@Profile("runner-fails")
@Order(1)
CommandLineRunner runnerOne() {
return args -> Trace.add("runner 1 ran");
}
@Bean
@Profile("runner-fails")
@Order(2)
ApplicationRunner runnerTwo() {
return args -> {
Trace.add("runner 2 is about to throw");
throw new IllegalStateException("boom from runner 2");
};
}
@Bean
@Profile("runner-fails")
@Order(3)
CommandLineRunner runnerThree() {
return args -> Trace.add("runner 3 ran");
}
// ---- profile ready-fails: an ApplicationReadyEvent listener throws -----------------------------------
@Component
@Profile("ready-fails")
static class ThrowingReadyListener {
private final ApplicationAvailability availability;
private final Environment env;
ThrowingReadyListener(ApplicationAvailability availability, Environment env) {
this.availability = availability;
this.env = env;
}
@EventListener
@Order(1)
void ready(ApplicationReadyEvent e) throws Exception {
String port = env.getProperty("server.port");
if (port != null) {
var response = java.net.http.HttpClient.newHttpClient().send(
java.net.http.HttpRequest.newBuilder(java.net.URI.create("http://localhost:" + port + "/ping")).build(),
java.net.http.HttpResponse.BodyHandlers.ofString());
Trace.add("GET /ping from inside the listener -> %d %s", response.statusCode(), response.body());
}
Trace.add("ready listener 1 is about to throw (readiness: %s)", availability.getReadinessState());
throw new IllegalStateException("boom from the ready listener");
}
@EventListener
@Order(2)
void secondListener(ApplicationReadyEvent e) {
Trace.add("ready listener 2 ran");
}
}
// ---- profile exit-code: a runner throws an exception that carries its own exit code ------------------
@Bean
@Profile("exit-code")
CommandLineRunner exitCodeRunner() {
return args -> {
throw new ExitWith42Exception("the data file is missing");
};
}
// ---- profile checked: a runner declares "throws Exception" and throws a checked one -------------------
@Bean
@Profile("checked")
CommandLineRunner checkedExceptionRunner() {
return args -> {
throw new java.io.IOException("cannot read data.csv");
};
}
static class ExitWith42Exception extends RuntimeException implements ExitCodeGenerator {
ExitWith42Exception(String message) {
super(message);
}
@Override
public int getExitCode() {
return 42;
}
}
}
@@ -0,0 +1,38 @@
package com.ankurm.runners.hello;
import java.util.Arrays;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
/** The smallest working example of all three hooks: each prints one line, so you can see the sequence. */
@SpringBootApplication
public class HelloApp {
public static void main(String[] args) {
SpringApplication.run(HelloApp.class, args);
}
@Bean
@Order(1)
CommandLineRunner commandLineRunner() {
return args -> System.out.println("hello: CommandLineRunner args = " + Arrays.toString(args));
}
@Bean
@Order(2)
ApplicationRunner applicationRunner() {
return args -> System.out.println("hello: ApplicationRunner options = " + args.getOptionNames()
+ ", non-option args = " + args.getNonOptionArgs());
}
@EventListener(ApplicationReadyEvent.class)
void onReady() {
System.out.println("hello: ApplicationReadyEvent listener");
}
}
@@ -0,0 +1,72 @@
package com.ankurm.runners.lifecycle;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* Scenario 9: five {@link Svc} lifecycle beans with different phases, one that must be started by hand and one that
* takes 300 ms to stop, next to a runner and the startup events.
*/
@SpringBootApplication
public class LifecycleApp {
public static void main(String[] args) {
SpringApplication.run(LifecycleApp.class, args);
}
@Bean
Svc high() {
return new Svc("high", 100, true, 0);
}
@Bean
Svc low() {
return new Svc("low", -100, true, 0);
}
@Bean
Svc mid() {
return new Svc("mid", 0, true, 0);
}
@Bean
Svc manual() {
return new Svc("manual", 50, false, 0);
}
@Bean
Svc slow() {
return new Svc("slow", 200, true, 300);
}
@Bean
CommandLineRunner runner() {
return args -> Trace.add("CommandLineRunner runs");
}
@Component
static class Events {
@EventListener
void started(ApplicationStartedEvent e) {
Trace.add("ApplicationStartedEvent");
}
@EventListener
void ready(ApplicationReadyEvent e) {
Trace.add("ApplicationReadyEvent");
}
@EventListener
void closing(ContextClosedEvent e) {
Trace.add("ContextClosedEvent (stop phase begins)");
}
}
}
@@ -0,0 +1,72 @@
package com.ankurm.runners.lifecycle;
import com.ankurm.runners.support.Trace;
import org.springframework.context.SmartLifecycle;
/** A {@link SmartLifecycle} that writes to the trace when it is started and stopped. */
public class Svc implements SmartLifecycle {
private final String name;
private final int phase;
private final boolean autoStartup;
private final long slowStopMillis;
private volatile boolean running;
public Svc(String name, int phase, boolean autoStartup, long slowStopMillis) {
this.name = name;
this.phase = phase;
this.autoStartup = autoStartup;
this.slowStopMillis = slowStopMillis;
}
@Override
public void start() {
running = true;
Trace.add("start %-6s (phase %d) on %s", name, phase, Trace.where());
}
@Override
public void stop() {
running = false;
Trace.add("stop %-6s (phase %d) on %s", name, phase, Trace.where());
}
/**
* The asynchronous stop: Spring waits for the callback (up to spring.lifecycle.timeout-per-shutdown-phase) before it moves
* on to the next phase. A bean with no slow shutdown simply keeps the default, which calls {@link #stop()} and then
* the callback.
*/
@Override
public void stop(Runnable callback) {
if (slowStopMillis == 0) {
SmartLifecycle.super.stop(callback);
return;
}
Trace.add("stop %-6s (phase %d) begins, will finish in %d ms", name, phase, slowStopMillis);
new Thread(() -> {
try {
Thread.sleep(slowStopMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
running = false;
Trace.add("stop %-6s finished, calling the callback", name);
callback.run();
}, "slow-stop").start();
}
@Override
public boolean isRunning() {
return running;
}
@Override
public boolean isAutoStartup() {
return autoStartup;
}
@Override
public int getPhase() {
return phase;
}
}
@@ -0,0 +1,37 @@
package com.ankurm.runners.lifeforgetful;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Bean;
/** Scenario 10b: a {@link SmartLifecycle} whose {@code isRunning()} always says false. */
@SpringBootApplication
public class ForgetfulApp {
public static void main(String[] args) {
SpringApplication.run(ForgetfulApp.class, args);
}
@Bean
SmartLifecycle forgetful() {
return new SmartLifecycle() {
@Override
public void start() {
Trace.add("start() was called");
// ... and the author forgot to remember that. isRunning() below never turns true.
}
@Override
public void stop() {
Trace.add("stop() was called");
}
@Override
public boolean isRunning() {
return false;
}
};
}
}
@@ -0,0 +1,88 @@
package com.ankurm.runners.lifestartfails;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/** Scenario 10a: a {@link SmartLifecycle#start()} that throws, next to a healthy one and a runner. */
@SpringBootApplication
public class StartFailsApp {
public static void main(String[] args) {
SpringApplication.run(StartFailsApp.class, args);
}
@Bean
SmartLifecycle healthy() {
return new Named("healthy", 0, false);
}
@Bean
SmartLifecycle broken() {
return new Named("broken", 10, true);
}
@Bean
CommandLineRunner runner() {
return args -> Trace.add("CommandLineRunner runs");
}
@Component
static class Events {
@EventListener
void started(ApplicationStartedEvent e) {
Trace.add("ApplicationStartedEvent");
}
@EventListener
void closing(ContextClosedEvent e) {
Trace.add("ContextClosedEvent");
}
}
static class Named implements SmartLifecycle {
private final String name;
private final int phase;
private final boolean failOnStart;
private volatile boolean running;
Named(String name, int phase, boolean failOnStart) {
this.name = name;
this.phase = phase;
this.failOnStart = failOnStart;
}
@Override
public void start() {
Trace.add("start %s (phase %d)", name, phase);
if (failOnStart) {
throw new IllegalStateException("could not connect to the broker");
}
running = true;
}
@Override
public void stop() {
running = false;
Trace.add("stop %s", name);
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return phase;
}
}
}
@@ -0,0 +1,47 @@
package com.ankurm.runners.order;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.web.server.context.WebServerInitializedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/** Listens to every startup event and also asks {@link ApplicationAvailability} what state the app thinks it is in. */
@Component
class EventProbe {
private final ApplicationAvailability availability;
EventProbe(ApplicationAvailability availability) {
this.availability = availability;
}
@EventListener
void webServer(WebServerInitializedEvent event) {
Trace.add("WebServerInitializedEvent (port is open)");
}
@EventListener
void refreshed(ContextRefreshedEvent event) {
Trace.add("ContextRefreshedEvent");
}
@EventListener
void started(ApplicationStartedEvent event) {
Trace.add("ApplicationStartedEvent");
}
@EventListener
void availabilityChanged(AvailabilityChangeEvent<?> event) {
Trace.add("AvailabilityChangeEvent -> %s", event.getState());
}
@EventListener
void ready(ApplicationReadyEvent event) {
Trace.add("ApplicationReadyEvent (readiness seen from inside: %s)", availability.getReadinessState());
}
}
@@ -0,0 +1,49 @@
package com.ankurm.runners.order;
import com.ankurm.runners.support.Trace;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
/**
* One bean that implements every "too early" hook plus {@link SmartLifecycle}, so the trace shows them in the order
* Spring really calls them.
*/
@Component
class LifecycleProbe implements InitializingBean, SmartInitializingSingleton, SmartLifecycle {
private boolean running;
@PostConstruct
void postConstruct() {
Trace.add("@PostConstruct");
}
@Override
public void afterPropertiesSet() {
Trace.add("InitializingBean.afterPropertiesSet");
}
@Override
public void afterSingletonsInstantiated() {
Trace.add("SmartInitializingSingleton.afterSingletonsInstantiated");
}
@Override
public void start() {
running = true;
Trace.add("SmartLifecycle.start (default phase)");
}
@Override
public void stop() {
running = false;
}
@Override
public boolean isRunning() {
return running;
}
}
@@ -0,0 +1,13 @@
package com.ankurm.runners.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** Scenario 1: where do the startup hooks run, relative to each other? Everything writes to {@code Trace}. */
@SpringBootApplication
public class OrderApp {
public static void main(String[] args) {
SpringApplication.run(OrderApp.class, args);
}
}
@@ -0,0 +1,46 @@
package com.ankurm.runners.order;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/** The two runner flavours. Explicit {@code @Order} values, because runners without one have no promised order. */
class Runners {
@Component
@Order(1)
static class Cli implements CommandLineRunner {
private final ApplicationAvailability availability;
Cli(ApplicationAvailability availability) {
this.availability = availability;
}
@Override
public void run(String... args) {
Trace.add("CommandLineRunner (readiness seen from inside: %s, liveness: %s)",
availability.getReadinessState(), availability.getLivenessState());
}
}
@Component
@Order(2)
static class App implements ApplicationRunner {
private final ApplicationAvailability availability;
App(ApplicationAvailability availability) {
this.availability = availability;
}
@Override
public void run(ApplicationArguments args) {
Trace.add("ApplicationRunner (readiness seen from inside: %s)", availability.getReadinessState());
}
}
}
@@ -0,0 +1,92 @@
package com.ankurm.runners.ordering;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* Scenario 2: seven runners of both kinds, with {@code @Order} on a class, on a {@code @Bean} method and through
* the {@link Ordered} interface, plus one with no order at all. The declaration order below is deliberately
* NOT the execution order.
*/
@SpringBootApplication
public class OrderingApp {
public static void main(String[] args) {
SpringApplication.run(OrderingApp.class, args);
}
/** {@code @Order} on a factory method: Spring Boot looks there too, not only on the class. */
@Bean
@Order(5)
CommandLineRunner cliOrderOnBeanMethod() {
return args -> Trace.add("CommandLineRunner @Order(5) on a @Bean method");
}
@Bean
ApplicationRunner arWithNoOrder() {
return args -> Trace.add("ApplicationRunner no order at all (lowest precedence)");
}
@Component
@Order(2)
static class CliTwo implements CommandLineRunner {
@Override
public void run(String... args) {
Trace.add("CommandLineRunner @Order(2) on the class");
}
}
@Component
@Order(1)
static class ArOne implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
Trace.add("ApplicationRunner @Order(1) on the class");
}
}
@Component
static class ArThree implements ApplicationRunner, Ordered {
@Override
public int getOrder() {
return 3;
}
@Override
public void run(ApplicationArguments args) {
Trace.add("ApplicationRunner implements Ordered, getOrder() = 3");
}
}
/** Implements both interfaces. Boot calls both methods, one after the other, at this one position. */
@Component
@Order(4)
static class Both implements CommandLineRunner, ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
Trace.add("Both @Order(4) -> ApplicationRunner.run");
}
@Override
public void run(String... args) {
Trace.add("Both @Order(4) -> CommandLineRunner.run");
}
}
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
static class First implements CommandLineRunner {
@Override
public void run(String... args) {
Trace.add("CommandLineRunner @Order(HIGHEST_PRECEDENCE)");
}
}
}
@@ -0,0 +1,16 @@
package com.ankurm.runners.slices;
import com.ankurm.runners.support.Trace;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/** A runner found by component scanning, which is what a test slice filters. */
@Component
class ComponentRunner implements CommandLineRunner {
@Override
public void run(String... args) {
Trace.add("CommandLineRunner from a top-level @Component ran, args = %s", Arrays.toString(args));
}
}
@@ -0,0 +1,14 @@
package com.ankurm.runners.slices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/** The one controller the {@code @WebMvcTest} slice is asked to load. */
@RestController
public class Hello {
@GetMapping("/hello")
String hello() {
return "hello";
}
}
@@ -0,0 +1,16 @@
package com.ankurm.runners.slices;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/** An {@code ApplicationReadyEvent} listener found by component scanning. */
@Component
class ReadyListener {
@EventListener
void ready(ApplicationReadyEvent e) {
Trace.add("ApplicationReadyEvent listener (a top-level @Component) ran");
}
}
@@ -0,0 +1,39 @@
package com.ankurm.runners.slices;
import com.ankurm.runners.support.Trace;
import java.util.Arrays;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* Scenario 11: what do tests do with runners? Four startup hooks declared four ways: a runner that is a top-level
* {@code @Component} ({@link ComponentRunner}), an {@code ApplicationReadyEvent} listener that is a top-level
* {@code @Component} ({@link ReadyListener}), a runner that is a {@code @Bean} method on this class, and a runner that is
* a {@code @Component} nested inside this class.
*/
@SpringBootApplication
public class SlicesApp {
public static void main(String[] args) {
SpringApplication.run(SlicesApp.class, args);
}
@Bean
ApplicationRunner runnerFromBeanMethod() {
return args -> Trace.add("ApplicationRunner from a @Bean method ran, source args = %s",
Arrays.toString(args.getSourceArgs()));
}
/** Nested in a configuration class: registered as a member class, so no component-scan filter can exclude it. */
@Component
static class NestedRunner implements CommandLineRunner {
@Override
public void run(String... args) {
Trace.add("CommandLineRunner nested in SlicesApp ran, args = %s", Arrays.toString(args));
}
}
}
@@ -0,0 +1,43 @@
package com.ankurm.runners.support;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A tiny in-memory log the scenarios write to and the tests print, so the order of startup steps is data and
* not a guess. When the system property {@code trace.echo} is set (the scenarios that start a second JVM do
* that), every line is also printed to stdout with a {@code TRACE } prefix so the parent test can collect it.
*/
public final class Trace {
private static final List<String> LINES = new CopyOnWriteArrayList<>();
private static final boolean ECHO = System.getProperty("trace.echo") != null;
private Trace() {
}
public static void add(String format, Object... args) {
String line = args.length == 0 ? format : String.format(format, args);
LINES.add(line);
if (ECHO) {
System.out.println("TRACE " + line);
}
}
/** Returns everything recorded so far and clears the log. */
public static List<String> drain() {
var copy = new ArrayList<>(LINES);
LINES.clear();
return copy;
}
/** Which kind of thread is running this code, in words that stay the same from run to run. */
public static String where() {
Thread t = Thread.currentThread();
if (t.isVirtual()) {
return "a virtual thread";
}
return t.getName().equals("main") ? "main" : "platform thread " + t.getName();
}
}
@@ -0,0 +1,40 @@
package com.ankurm.runners.ties;
import com.ankurm.runners.support.Trace;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
/**
* Scenario 3: four runners and no {@code @Order} anywhere. The test starts this in several fresh JVMs and
* records the order each one chose.
*/
@SpringBootApplication
public class TiesApp {
public static void main(String[] args) {
SpringApplication.run(TiesApp.class, args);
}
@Bean
CommandLineRunner cliA() {
return args -> Trace.add("cliA");
}
@Bean
ApplicationRunner arB() {
return args -> Trace.add("arB");
}
@Bean
CommandLineRunner cliC() {
return args -> Trace.add("cliC");
}
@Bean
ApplicationRunner arD() {
return args -> Trace.add("arD");
}
}
@@ -0,0 +1,114 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.blocking.BlockingApp;
import com.ankurm.runners.blocking.Gate;
import com.ankurm.runners.support.Trace;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
/** Sections 7 and 8: a slow runner delays readiness; a runner that hands its work to another thread does not. */
class BlockingTests {
private static final HttpClient HTTP = HttpClient.newHttpClient();
private static int freePort() throws IOException {
try (var s = new ServerSocket(0)) {
return s.getLocalPort();
}
}
private static String get(int port, String path) throws Exception {
var r = HTTP.send(HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)).build(),
HttpResponse.BodyHandlers.ofString());
return String.format("%-32s -> %d %s", "GET " + path, r.statusCode(), r.body());
}
private static Thread startInBackground(AtomicReference<BootRun.Result> result, int port, String profile) {
var thread = new Thread(() -> result.set(BootRun.run(BlockingApp.class, WebApplicationType.SERVLET,
"server.port=" + port,
"spring.profiles.active=" + profile,
"management.endpoint.health.probes.enabled=true",
"management.endpoints.web.exposure.include=health")), "app-main");
thread.start();
return thread;
}
@Test
void aBlockingRunnerKeepsReadinessDownAndSpringApplicationRunOpen() throws Exception {
try (var t = new Transcript("07-blocking-runner-readiness.txt",
"A runner that blocks: the port is open, liveness is UP, readiness is OUT_OF_SERVICE")) {
Trace.drain();
Gate.reset();
int port = freePort();
var result = new AtomicReference<BootRun.Result>();
var app = startInBackground(result, port, "blocking");
assertThat(Gate.RUNNER_STARTED.await(60, TimeUnit.SECONDS)).isTrue();
t.section("while the runner is blocked");
t.line("has SpringApplication.run() returned? %s", result.get() != null);
String ping = get(port, "/ping");
String live = get(port, "/actuator/health/liveness");
String ready = get(port, "/actuator/health/readiness");
t.line(ping);
t.line(live);
t.line(ready);
assertThat(ping).contains("200 pong");
assertThat(live).contains("200");
assertThat(ready).contains("503");
Gate.RELEASE.countDown();
app.join(30_000);
t.section("after the runner returned");
t.line("has SpringApplication.run() returned? %s", result.get() != null);
String readyAfter = get(port, "/actuator/health/readiness");
t.line(readyAfter);
assertThat(readyAfter).contains("200");
t.section("trace");
Trace.drain().forEach(t::line);
result.get().close();
}
}
@Test
void aRunnerThatHandsOffItsWorkLetsTheApplicationBecomeReadyAtOnce() throws Exception {
try (var t = new Transcript("08-async-runner.txt",
"A runner that starts a virtual thread and returns: readiness does not wait, and failures do not fail startup")) {
Trace.drain();
Gate.reset();
int port = freePort();
var result = new AtomicReference<BootRun.Result>();
var app = startInBackground(result, port, "async");
app.join(60_000);
assertThat(result.get()).isNotNull();
assertThat(result.get().started()).isTrue();
t.section("the background work is still waiting");
t.line("has SpringApplication.run() returned? %s", true);
String ready = get(port, "/actuator/health/readiness");
t.line(ready);
assertThat(ready).contains("200");
Gate.RELEASE.countDown();
assertThat(Gate.BACKGROUND_DONE.await(30, TimeUnit.SECONDS)).isTrue();
t.section("after the background work threw");
String readyAfter = get(port, "/actuator/health/readiness");
t.line(readyAfter);
t.line(get(port, "/ping"));
assertThat(readyAfter).contains("200");
t.section("trace");
Trace.drain().forEach(t::line);
result.get().close();
}
}
}
@@ -0,0 +1,56 @@
package com.ankurm.runners;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
/** Starts a Spring Boot application in this JVM and returns either the context or the failure. */
public final class BootRun {
private BootRun() {
}
public static Result runWithArgs(Class<?> source, WebApplicationType type, String[] args, String... properties) {
var props = new ArrayList<String>();
props.add("spring.main.banner-mode=off");
props.add("logging.level.root=OFF");
props.addAll(List.of(properties));
try {
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(source)
.web(type)
.properties(props.toArray(String[]::new))
.run(args);
return new Result(ctx, null);
} catch (RuntimeException e) {
return new Result(null, e);
}
}
public static Result run(Class<?> source, WebApplicationType type, String... properties) {
return runWithArgs(source, type, new String[0], properties);
}
/** Names the exception classes from the outside in, with the message of each one. */
public static List<String> chain(Throwable t) {
var lines = new ArrayList<String>();
for (Throwable c = t; c != null; c = (c.getCause() == c) ? null : c.getCause()) {
lines.add(c.getClass().getName() + ": " + c.getMessage());
}
return lines;
}
public record Result(ConfigurableApplicationContext context, RuntimeException failure) {
public boolean started() {
return failure == null;
}
public void close() {
if (context != null) {
context.close();
}
}
}
}
@@ -0,0 +1,86 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.failure.FailureApp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import org.junit.jupiter.api.Test;
/** Sections 5 and 6: what happens when a runner throws, and when an ApplicationReadyEvent listener throws. */
class FailureTests {
private static int freePort() throws IOException {
try (var s = new ServerSocket(0)) {
return s.getLocalPort();
}
}
private static boolean portAnswers(int port) {
try (var s = new Socket()) {
s.connect(new InetSocketAddress("localhost", port), 500);
return true;
} catch (IOException e) {
return false;
}
}
@Test
void aRunnerThatThrowsStopsTheApplication() {
try (var t = new Transcript("05-runner-failure.txt",
"A runner throws: exit code, log, events, and the runners that never ran")) {
t.section("three ordered runners, the second throws (non-web, in a separate JVM)");
var r = Forked.run(FailureApp.class,
List.of("--spring.profiles.active=runner-fails", "--spring.main.web-application-type=none"));
r.trace().forEach(l -> t.line("TRACE %s", l));
r.errorLog().forEach(t::line);
t.line("process exit code: %d", r.exitCode());
assertThat(r.exitCode()).isEqualTo(1);
assertThat(r.trace()).contains("runner 1 ran", "runner 2 is about to throw");
assertThat(r.trace()).doesNotContain("runner 3 ran");
assertThat(r.trace().stream().filter(l -> l.startsWith("ApplicationReadyEvent"))).isEmpty();
t.section("a runner exception that implements ExitCodeGenerator");
var e = Forked.run(FailureApp.class,
List.of("--spring.profiles.active=exit-code", "--spring.main.web-application-type=none"));
e.errorLog().forEach(t::line);
t.line("process exit code: %d", e.exitCode());
assertThat(e.exitCode()).isEqualTo(42);
t.section("a runner that throws a checked exception (declared with throws Exception)");
var c = Forked.run(FailureApp.class,
List.of("--spring.profiles.active=checked", "--spring.main.web-application-type=none"));
c.errorLog().forEach(t::line);
t.line("process exit code: %d", c.exitCode());
assertThat(c.exitCode()).isEqualTo(1);
}
}
@Test
void aReadyListenerThatThrowsAlsoStopsTheApplication() throws Exception {
try (var t = new Transcript("06-ready-listener-failure.txt",
"An ApplicationReadyEvent listener throws: the app was 'ready' and is now gone")) {
t.section("non-web application");
var r = Forked.run(FailureApp.class,
List.of("--spring.profiles.active=ready-fails", "--spring.main.web-application-type=none"));
r.trace().forEach(l -> t.line("TRACE %s", l));
r.errorLog().forEach(t::line);
t.line("process exit code: %d", r.exitCode());
assertThat(r.exitCode()).isEqualTo(1);
t.section("web application (Tomcat is up when the listener runs)");
int port = freePort();
var w = Forked.run(FailureApp.class,
List.of("--spring.profiles.active=ready-fails", "--server.port=" + port));
w.trace().forEach(l -> t.line("TRACE %s", l));
w.errorLog().forEach(t::line);
t.line("process exit code: %d", w.exitCode());
t.line("does the port answer after the process ended? %s", portAnswers(port));
assertThat(w.exitCode()).isEqualTo(1);
assertThat(portAnswers(port)).isFalse();
}
}
}
@@ -0,0 +1,78 @@
package com.ankurm.runners;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Runs an application's {@code main} in a second JVM with the test classpath, so the test can see what a real
* {@code java -cp ... Main} does: the exit code and everything written to the console.
*/
public final class Forked {
private Forked() {
}
public record Result(int exitCode, List<String> output) {
/** The lines the scenario wrote with {@code Trace.add}, without the {@code TRACE } prefix. */
public List<String> trace() {
return output.stream().filter(l -> l.startsWith("TRACE ")).map(l -> l.substring(6)).toList();
}
/**
* The log lines worth quoting: the ERROR line and the exception headers ("java.lang.X: message" and
* "Caused by: ..."), without stack frames. The pattern is fixed in {@link #LOG_PATTERN}, so there is no
* timestamp or pid in them.
*/
public List<String> errorLog() {
return output.stream()
.filter(l -> l.startsWith("ERROR ") || l.matches("(Caused by: )?[\\w.$]+(Exception|Error)(: .*)?"))
.toList();
}
}
/** A log line without timestamp, pid or thread id, so a transcript does not change from run to run. */
public static final String LOG_PATTERN = "%-5level %logger{24} : %msg%n%wEx";
public static Result run(Class<?> main, List<String> args) {
return run(main, List.of(), args);
}
/** {@code jvmOptions} go before the main class (for example {@code -Dspring.main.web-application-type=none}). */
public static Result run(Class<?> main, List<String> jvmOptions, List<String> args) {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
var cmd = new ArrayList<String>();
cmd.add(java);
cmd.add("-Dtrace.echo=true");
cmd.add("-Dspring.main.banner-mode=off");
cmd.add("-Dlogging.pattern.console=" + LOG_PATTERN);
cmd.addAll(jvmOptions);
cmd.add("-cp");
cmd.add(System.getProperty("java.class.path"));
cmd.add(main.getName());
cmd.addAll(args);
try {
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
var lines = new ArrayList<String>();
try (var r = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
String l;
while ((l = r.readLine()) != null) {
lines.add(l);
}
}
if (!p.waitFor(60, TimeUnit.SECONDS)) {
p.destroyForcibly();
throw new IllegalStateException("forked JVM did not exit in 60 s: " + lines);
}
return new Result(p.exitValue(), lines);
} catch (IOException | InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,25 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.hello.HelloApp;
import java.util.List;
import org.junit.jupiter.api.Test;
/** Section 1: the smallest working example, run the way a user would run it: a real JVM and a real command line. */
class HelloTests {
@Test
void allThreeHooksPrintOneLineEach() {
try (var t = new Transcript("00-hello.txt", "HelloApp started with: --greeting=hi --verbose notes.txt")) {
var r = Forked.run(HelloApp.class,
List.of("-Dspring.main.web-application-type=none"), List.of("--greeting=hi", "--verbose", "notes.txt"));
var lines = r.output().stream().filter(l -> l.startsWith("hello:")).toList();
lines.forEach(t::line);
t.line("process exit code: %d", r.exitCode());
assertThat(r.exitCode()).isZero();
assertThat(lines).hasSize(3);
assertThat(lines.get(2)).isEqualTo("hello: ApplicationReadyEvent listener");
}
}
}
@@ -0,0 +1,97 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.lifecycle.LifecycleApp;
import com.ankurm.runners.lifecycle.Svc;
import com.ankurm.runners.lifeforgetful.ForgetfulApp;
import com.ankurm.runners.lifestartfails.StartFailsApp;
import com.ankurm.runners.support.Trace;
import java.util.Comparator;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.SpringVersion;
import org.springframework.test.util.ReflectionTestUtils;
/** Sections 9 and 10: SmartLifecycle phases, start, stop, and the two ways it goes wrong. */
class LifecycleTests {
@Test
void phasesDecideTheOrderAndStopRunsBackwards() {
try (var t = new Transcript("09-smartlifecycle-phases.txt",
"SmartLifecycle: start in ascending phase, stop in descending phase, runners after all of it")) {
Trace.drain();
var run = BootRun.run(LifecycleApp.class, WebApplicationType.NONE);
t.section("startup");
Trace.drain().forEach(t::line);
var manual = run.context().getBean("manual", Svc.class);
t.line("manual.isAutoStartup()=%s isRunning()=%s (never started by the context)", manual.isAutoStartup(), manual.isRunning());
manual.start();
t.section("context.close()");
run.close();
var stop = Trace.drain();
stop.forEach(t::line);
assertThat(stop.stream().filter(l -> l.startsWith("stop")).map(l -> l.split("\\s+")[1]).distinct().toList())
.containsExactly("slow", "high", "manual", "mid", "low");
assertThat(stop).contains("stop slow finished, calling the callback");
}
}
@Test
void theWebServerIsJustTwoMoreLifecycleBeans() {
try (var t = new Transcript("10-lifecycle-beans-in-a-web-app.txt",
"Every SmartLifecycle bean in a servlet web application, by phase (the ones this project adds are marked)")) {
var run = BootRun.run(LifecycleApp.class, WebApplicationType.SERVLET, "server.port=0");
var ctx = run.context();
ctx.getBeansOfType(SmartLifecycle.class).entrySet().stream()
.sorted(Comparator.comparingInt(e -> e.getValue().getPhase()))
.forEach(e -> t.line("phase %11d %-30s %s", e.getValue().getPhase(), e.getKey(),
e.getValue() instanceof Svc ? "(this project)" : e.getValue().getClass().getSimpleName()));
t.line("SmartLifecycle.DEFAULT_PHASE = %d", SmartLifecycle.DEFAULT_PHASE);
t.line("Integer.MAX_VALUE = %d", Integer.MAX_VALUE);
t.line("timeout per shutdown phase = %s ms (spring.lifecycle.timeout-per-shutdown-phase, set by Boot)",
ReflectionTestUtils.getField(ctx.getBean("lifecycleProcessor"), "timeoutPerShutdownPhase"));
t.line("Spring Boot %s, Spring Framework %s", SpringBootVersion.getVersion(), SpringVersion.getVersion());
assertThat(ctx.getBeansOfType(SmartLifecycle.class)).containsKeys("webServerStartStop", "webServerGracefulShutdown");
run.close();
Trace.drain();
}
}
@Test
void aSmartLifecycleThatThrowsOnStartFailsTheApplicationBeforeAnyRunner() {
try (var t = new Transcript("11-smartlifecycle-start-fails.txt",
"SmartLifecycle.start() throws: no ApplicationStartedEvent, no runner")) {
Trace.drain();
var run = BootRun.run(StartFailsApp.class, WebApplicationType.NONE);
var lines = Trace.drain();
lines.forEach(t::line);
t.blank();
t.line("application started? %s", run.started());
BootRun.chain(run.failure()).forEach(l -> t.line(" %s", l));
assertThat(run.started()).isFalse();
assertThat(lines).doesNotContain("CommandLineRunner runs", "ApplicationStartedEvent");
}
}
@Test
void aSmartLifecycleThatNeverReportsRunningIsNeverStopped() {
try (var t = new Transcript("12-smartlifecycle-forgot-isrunning.txt",
"isRunning() always false: start() is called, stop() never is")) {
Trace.drain();
var run = BootRun.run(ForgetfulApp.class, WebApplicationType.NONE);
t.line("--- startup ---");
Trace.drain().forEach(t::line);
run.close();
t.line("--- after context.close() ---");
var afterClose = Trace.drain();
afterClose.forEach(t::line);
if (afterClose.isEmpty()) {
t.line("(nothing)");
}
assertThat(afterClose).isEmpty();
}
}
}
@@ -0,0 +1,46 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.order.OrderApp;
import com.ankurm.runners.support.Trace;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
/** Section 2: where each startup hook runs, printed from a real run. */
class OrderTests {
@Test
void theHooksRunInOneFixedSequence() {
try (var t = new Transcript("01-startup-hooks-in-order.txt",
"Every startup hook in the order Spring Boot 4.1.2 really calls it")) {
t.section("non-web application");
Trace.drain();
var plain = BootRun.run(OrderApp.class, WebApplicationType.NONE);
List<String> noWeb = Trace.drain();
noWeb.forEach(t::line);
plain.close();
t.section("servlet web application (Tomcat on a random port)");
var web = BootRun.run(OrderApp.class, WebApplicationType.SERVLET, "server.port=0");
List<String> withWeb = Trace.drain();
withWeb.forEach(t::line);
web.close();
assertThat(noWeb).containsExactly(
"@PostConstruct",
"InitializingBean.afterPropertiesSet",
"SmartInitializingSingleton.afterSingletonsInstantiated",
"SmartLifecycle.start (default phase)",
"ContextRefreshedEvent",
"ApplicationStartedEvent",
"AvailabilityChangeEvent -> CORRECT",
"CommandLineRunner (readiness seen from inside: REFUSING_TRAFFIC, liveness: CORRECT)",
"ApplicationRunner (readiness seen from inside: REFUSING_TRAFFIC)",
"ApplicationReadyEvent (readiness seen from inside: REFUSING_TRAFFIC)",
"AvailabilityChangeEvent -> ACCEPTING_TRAFFIC");
assertThat(withWeb).contains("WebServerInitializedEvent (port is open)");
}
}
}
@@ -0,0 +1,79 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.args.ArgsApp;
import com.ankurm.runners.ordering.OrderingApp;
import com.ankurm.runners.support.Trace;
import com.ankurm.runners.ties.TiesApp;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
/** Sections 3 and 4: ordering between runners, and the arguments each flavour receives. */
class RunnerTests {
@Test
void orderAnnotationsSortBothFlavoursIntoOneList() {
try (var t = new Transcript("02-order-annotation-and-ordered.txt",
"CommandLineRunner and ApplicationRunner beans sorted together by @Order / Ordered")) {
Trace.drain();
var run = BootRun.run(OrderingApp.class, WebApplicationType.NONE);
var lines = Trace.drain();
run.close();
t.line("(declaration order in OrderingApp.java is NOT the order below)");
t.blank();
lines.forEach(t::line);
assertThat(lines).containsExactly(
"CommandLineRunner @Order(HIGHEST_PRECEDENCE)",
"ApplicationRunner @Order(1) on the class",
"CommandLineRunner @Order(2) on the class",
"ApplicationRunner implements Ordered, getOrder() = 3",
"Both @Order(4) -> ApplicationRunner.run",
"Both @Order(4) -> CommandLineRunner.run",
"CommandLineRunner @Order(5) on a @Bean method",
"ApplicationRunner no order at all (lowest precedence)");
}
}
@Test
void runnersWithTheSameOrderHaveNoPromisedSequence() {
// Every run is a fresh JVM, because the sequence comes from identity hash codes, which change per JVM.
try (var t = new Transcript("03-ties-have-no-promised-order.txt",
"Four runners without @Order: the order chosen by each of 8 fresh JVMs")) {
Map<String, Integer> seen = new LinkedHashMap<>();
for (int i = 1; i <= 8; i++) {
var result = Forked.run(TiesApp.class, List.of("--spring.main.web-application-type=none"));
assertThat(result.exitCode()).isZero();
String order = String.join(" ", result.trace());
t.line("JVM %d: %s", i, order);
seen.merge(order, 1, Integer::sum);
}
t.blank();
t.line("distinct sequences seen: %d", seen.size());
seen.forEach((order, n) -> t.line(" %-22s x%d", order, n));
// The contract is only "all four ran". How many distinct sequences appear is exactly what is not promised.
seen.keySet().forEach(order -> assertThat(order.split(" ")).containsExactlyInAnyOrder("cliA", "arB", "cliC", "arD"));
}
}
@Test
void theTwoFlavoursSeeTheSameCommandLineDifferently() {
try (var t = new Transcript("04-arguments.txt", "The same command line, seen by CommandLineRunner and ApplicationRunner")) {
String[] args = {"--name=Ankur", "--verbose", "--name=Second", "data.csv", "-x", "--", "--after-the-dashes"};
t.line("args passed to SpringApplication.run: %s", java.util.Arrays.toString(args));
t.blank();
Trace.drain();
var run = BootRun.runWithArgs(ArgsApp.class, WebApplicationType.NONE, args);
var lines = Trace.drain();
var name = run.context().getEnvironment().getProperty("name");
run.close();
lines.forEach(t::line);
t.blank();
t.line("Environment property 'name' (both values, joined by a comma): %s", name);
assertThat(lines).hasSize(8);
}
}
}
@@ -0,0 +1,30 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.slices.SlicesApp;
import com.ankurm.runners.support.Trace;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/** Section 11: {@code @SpringBootTest} starts the application through SpringApplication, so every startup hook runs. */
@SpringBootTest(classes = SlicesApp.class, args = "--from-the-test=1")
class SpringBootTestHooksTests {
@BeforeAll
static void clear() {
Trace.drain();
}
@Test
void springBootTestRunsRunnersAndTheReadyEvent() {
List<String> lines = Trace.drain();
try (var t = new Transcript("13-spring-boot-test-runs-the-hooks.txt",
"@SpringBootTest(classes = SlicesApp.class, args = \"--from-the-test=1\"): what ran before the first test method")) {
lines.forEach(t::line);
}
assertThat(lines).hasSize(4);
}
}
@@ -0,0 +1,54 @@
package com.ankurm.runners;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Writes a numbered transcript under {@code output/} and echoes it to the console.
* Every console block quoted in the article comes out of one of these files verbatim.
*/
public final class Transcript implements AutoCloseable {
private final Path path;
private final StringWriter buffer = new StringWriter();
private final PrintWriter out = new PrintWriter(buffer);
public Transcript(String fileName, String title) {
this.path = Path.of("output", fileName);
out.println("# " + title);
out.println();
}
public Transcript line(String format, Object... args) {
out.println(args.length == 0 ? format : String.format(format, args));
return this;
}
public Transcript blank() {
out.println();
return this;
}
public Transcript section(String heading) {
out.println();
out.println("--- " + heading + " ---");
return this;
}
@Override
public void close() {
out.flush();
// Absolute paths of whoever ran the build are environment noise, not a finding.
String text = buffer.toString().replace(System.getProperty("user.dir"), "<startup-runners>");
try {
Files.createDirectories(path.getParent());
Files.writeString(path, text);
} catch (IOException e) {
throw new IllegalStateException("could not write " + path, e);
}
System.out.print(text);
}
}
@@ -0,0 +1,36 @@
package com.ankurm.runners;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.runners.slices.Hello;
import com.ankurm.runners.slices.SlicesApp;
import com.ankurm.runners.support.Trace;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.test.context.ContextConfiguration;
/** Section 11: {@code @WebMvcTest} keeps the {@code @Bean} method (it is on the configuration class) and drops the rest. */
@WebMvcTest(controllers = Hello.class)
@ContextConfiguration(classes = SlicesApp.class)
class WebMvcSliceTests {
@BeforeAll
static void clear() {
Trace.drain();
}
@Test
void aWebMvcSliceDropsScannedComponentsButKeepsBeanMethodsAndNestedClasses() {
List<String> lines = Trace.drain();
try (var t = new Transcript("14-webmvctest-slice-hooks.txt",
"@WebMvcTest(controllers = Hello.class): what ran before the first test method")) {
lines.forEach(t::line);
if (lines.isEmpty()) {
t.line("(nothing)");
}
}
assertThat(lines).hasSize(2);
}
}