Spring Boot DevTools: faster restarts during development
DevTools restarts a Spring Boot application inside the same JVM whenever its classes change, keeping library classes loaded in a separate class loader. This page explains how that works, runs DevTools restarting a live application, and shows the cast and deserialization errors the class loader split causes.
Contents
What Spring Boot DevTools does Adding DevTools, and when it switches itself off Watching DevTools restart an application Why a restart is faster than a cold start Two class loaders, and the ClassCastException they cause Deserialization after a restart Configuring restart and the development defaults Remote DevTools, LiveReload and alternatives Choosing a development loop
What Spring Boot DevTools does
During development, the slowest part of the edit-run cycle is often restarting the application to see a change. Spring Boot DevTools shortens that loop. It is a single dependency, spring-boot-devtools
- Automatic restart: it watches the classpath, and when compiled classes change, it restarts the application context inside the same JVM, usually much faster than a cold start.
- Development property defaults: it switches off template and resource caching and turns on detailed error pages, so a change to a template is visible at once.
- Global settings: properties in
apply to every Spring Boot project on the machine.$HOME/.config/spring-boot/spring-boot-devtools.properties - LiveReload and remote support: a LiveReload server for browser refreshes, deprecated since Spring Boot 4.1.0 with no replacement, and an opt-in remote mode for applications running elsewhere.
The restart works because of a split between two class loaders. The base class loader loads classes that do not change during development: the JDK and every library jar. A restart class loader loads the project's own classes, the ones your IDE recompiles. On a change, DevTools closes the application context, throws away the restart class loader, creates a new one that reads the fresh class files, and runs the application's main
| Feature | On by default | Controlled by |
|---|---|---|
| Automatic restart | Yes | spring.devtools.restart.enabled |
| Development property defaults | Yes | spring.devtools.add-properties |
| Condition evaluation delta logged on restart | Yes | spring.devtools.restart.log-condition-evaluation-delta |
| LiveReload server (deprecated in 4.1) | Yes | spring.devtools.livereload.enabled |
| Remote restart | No | spring.devtools.remote.secret |
The programs on this page ran with Spring Boot 4.1.2, spring-boot-devtools
Adding DevTools, and when it switches itself off
DevTools must never reach production, so both build tools declare it in a way that keeps it out of other modules and out of the packaged jar:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
dependencies {
developmentOnly("org.springframework.boot:spring-boot-devtools")
}
in Maven and theoptional configuration in Gradle stop DevTools from being passed on to projects that depend on this one.developmentOnly- The Spring Boot plugins leave DevTools out of the repackaged fat jar by default. The Maven plugin's
option controls that, and only remote DevTools needs it set toexcludeDevtools .false - At runtime, DevTools treats an application started with
, or from a special class loader, as a production application and disables itself.java -jar turns restart off, and-Dspring.devtools.restart.enabled=false forces it on even where DevTools would disable it, which the documentation warns must never be done in production.true
The restart setting is read before the application context exists, so it has to be a system property rather than an entry in application.propertiesSpringApplication.run
package devtools.switches;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.devtools.classpath.ClassPathFileSystemWatcher;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class DevToolsSwitches {
static int mainCalls;
public static void main(String[] args) {
mainCalls++;
// Read before the application context exists, so it must be a system property.
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication app = new SpringApplication(DevToolsSwitches.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"server.port", "0"));
try (ConfigurableApplicationContext context = app.run(args)) {
System.out.println("With spring.devtools.restart.enabled=false:");
System.out.println(" thread: " + Thread.currentThread().getName()
+ ", main() calls: " + mainCalls);
System.out.println(" app class loaded by "
+ DevToolsSwitches.class.getClassLoader().getClass().getSimpleName());
System.out.println(" class path watchers: "
+ context.getBeansOfType(ClassPathFileSystemWatcher.class).size());
System.out.println(" spring.web.error.include-stacktrace = "
+ context.getEnvironment().getProperty("spring.web.error.include-stacktrace"));
}
}
}
With spring.devtools.restart.enabled=false:
thread: main, main() calls: 1
app class loaded by AppClassLoader
class path watchers: 0
spring.web.error.include-stacktrace = null
ran once, on themain() thread, and the application class came from the JDK'smain : DevTools did not take over the start.AppClassLoader- No
bean was created, so no file change could trigger a restart.ClassPathFileSystemWatcher wasspring.web.error.include-stacktrace . Turning restart off also removed the development property defaults, because DevTools adds them only once its restarter has been set up, or when remote restart is configured. In the next program, with restart on, the same property wasnull .always
Restarts are triggered by changes to compiled classes, so the IDE has to compile on save. Eclipse does so by default; in IntelliJ IDEA, use Build Project, or enable automatic building. Running ./mvnw spring-boot:run./gradlew bootRun
Watching DevTools restart an application
This program runs under DevTools as an IDE would run it: from a directory of compiled classes, with the DevTools jar among the libraries. It uses a trigger file, so that it can change a file, show that nothing happens yet, and then ask for the restart. State that must outlive the restart is kept in System.getProperties()
package devtools.live;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
@SpringBootApplication
public class DevToolsRestart {
static int staticCounter;
record Note(String text) { }
static String loaderName(Class<?> type) {
return type.getClassLoader().getClass().getSimpleName();
}
public static void main(String[] args) throws Exception {
staticCounter++;
System.out.println("main() on thread '" + Thread.currentThread().getName()
+ "', app class loaded by " + loaderName(DevToolsRestart.class));
Path classes = Path.of(DevToolsRestart.class.getProtectionDomain()
.getCodeSource().getLocation().toURI());
if (Thread.currentThread().getName().equals("main")) {
Files.deleteIfExists(classes.resolve("changed.txt"));
Files.deleteIfExists(classes.resolve("restart.trigger"));
}
SpringApplication app = new SpringApplication(DevToolsRestart.class);
Map<String, Object> props = new HashMap<>(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"logging.level.org.springframework.boot.devtools", "INFO",
"logging.pattern.console", "[log] %msg%n",
"spring.devtools.restart.trigger-file", "restart.trigger",
"server.port", "0"));
app.setDefaultProperties(props);
ConfigurableApplicationContext context = app.run(args);
Properties shared = System.getProperties();
int run = Integer.parseInt(shared.getProperty("demo.run", "0")) + 1;
shared.setProperty("demo.run", String.valueOf(run));
System.out.println("Run " + run + ": staticCounter = " + staticCounter
+ ", Spring classes loaded by " + loaderName(SpringApplication.class));
if (run == 1) {
Environment env = context.getEnvironment();
for (String key : new String[] {"spring.web.error.include-stacktrace",
"server.servlet.session.persistent", "spring.mvc.log-resolved-exception"}) {
System.out.println(" " + key + " = " + env.getProperty(key));
}
shared.put("demo.note", new Note("cached in run 1"));
shared.put("demo.loader", DevToolsRestart.class.getClassLoader());
Files.writeString(classes.resolve("changed.txt"), "a recompiled file");
Thread.sleep(3000);
System.out.println("3 s after changing a file, still in run "
+ shared.getProperty("demo.run") + ": no trigger file yet");
Files.writeString(classes.resolve("restart.trigger"), "go");
return;
}
System.out.println(" same class loader as run 1: "
+ (shared.get("demo.loader") == DevToolsRestart.class.getClassLoader()));
try {
Note note = (Note) shared.get("demo.note");
System.out.println(" cached note: " + note.text());
} catch (ClassCastException e) {
String message = e.getMessage().replaceAll("@[0-9a-f]+", "@<id>")
.replace(" (", "\n (").replace("; ", ";\n ");
System.out.println(" " + e.getClass().getSimpleName() + ": " + message);
}
context.close();
// DevTools ended the original main thread with an exception, so the java
// launcher would report exit code 1 when the JVM stops on its own.
System.exit(0);
}
}
main() on thread 'main', app class loaded by AppClassLoader
main() on thread 'restartedMain', app class loaded by RestartClassLoader
[log] Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
[log] For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
Run 1: staticCounter = 1, Spring classes loaded by AppClassLoader
spring.web.error.include-stacktrace = always
server.servlet.session.persistent = true
spring.mvc.log-resolved-exception = true
3 s after changing a file, still in run 1: no trigger file yet
[log] Restarting due to 1 class path change (1 addition, 0 deletions, 0 modifications)
main() on thread 'restartedMain', app class loaded by RestartClassLoader
[log] Condition evaluation unchanged
Run 2: staticCounter = 1, Spring classes loaded by AppClassLoader
same class loader as run 1: false
ClassCastException: class devtools.live.DevToolsRestart$Note cannot be cast to class devtools.live.DevToolsRestart$Note
(devtools.live.DevToolsRestart$Note is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @<id>;
devtools.live.DevToolsRestart$Note is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @<id>)
was called three times. The first call, on themain() thread with the JDK'smain , never got pastAppClassLoader : DevTools stopped it there and calledapp.run again on a thread namedmain() , with the application class loaded by itsrestartedMain . This happens on every start, before any file has changed.RestartClassLoader- The
lines are DevTools' own INFO messages. The first says the development property defaults were added, and the values printed for run 1 are three of them:[log] ,always andtrue , none of which the program set.true - Three seconds after
appeared in the classes directory, the program was still in run 1. With a trigger file configured, DevTools noticed nothing untilchanged.txt was written; it then logged "Restarting due to 1 class path change (1 addition, 0 deletions, 0 modifications)". The change it counted wasrestart.trigger , not the trigger file.changed.txt - Run 2 printed
again. The new class loader loadedstaticCounter = 1 afresh, so its static fields started from their initial values, while the counter in the system properties, owned by the base loader, went from 1 to 2. Spring's own classes were still loaded byDevToolsRestart .AppClassLoader - "Condition evaluation unchanged" is the condition evaluation delta: after a restart, DevTools logs which auto-configurations changed, and here none did.
- The
cached in run 1 could not be cast to run 2'sNote . The message names two classes calledNote , each in a differentDevToolsRestart$Note ; the section on class loaders below explains this error.RestartClassLoader
Two details showed up only when running it. Writing the trigger file alone, without another changed file, did not restart the application, because DevTools leaves the trigger file out of the change set it inspects. And DevTools ends the original mainjavaSystem.exit(0)
Why a restart is faster than a cold start
A restart keeps the JVM and every library class it has already loaded and compiled. This program starts the same web application four times in one JVM, calls it each time, and compares the first start with the best of the others, which is what a DevTools restart saves:
package devtools.restart;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class WarmRestart {
static int generation;
@GetMapping("/version")
String version() {
return "generation " + generation;
}
static long startServeStop() throws Exception {
generation++;
long begin = System.nanoTime();
SpringApplication app = new SpringApplication(WarmRestart.class);
app.setDefaultProperties(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (var context = app.run()) {
long millis = (System.nanoTime() - begin) / 1000000;
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String body = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/version"))
.build(), HttpResponse.BodyHandlers.ofString()).body();
System.out.println(" context " + generation + " answered: " + body);
return millis;
}
}
public static void main(String[] args) throws Exception {
System.out.println("Starting, stopping and starting the context again in one JVM:");
long cold = startServeStop();
long warm = Long.MAX_VALUE;
for (int i = 0; i < 3; i++) {
warm = Math.min(warm, startServeStop());
}
System.out.println("Rough comparison: the best warm start took "
+ (warm * 100 / cold < 50 ? "under half" : "more than half")
+ " the time of the cold start");
}
}
Starting, stopping and starting the context again in one JVM:
context 1 answered: generation 1
context 2 answered: generation 2
context 3 answered: generation 3
context 4 answered: generation 4
Rough comparison: the best warm start took under half the time of the cold start
- All four contexts started on a random port and answered
, and each was closed before the next started, as DevTools closes the old context before creating the new one./version - The best warm start took under half the time of the cold start. This is a rough comparison on a 2-core Intel Xeon at 2.1 GHz; the exact times vary, but the gap is large because the first start also loads and links thousands of Spring, Tomcat and Jackson classes.
- The static counter
kept counting from 1 to 4, because this program reuses the same classes. Under DevTools, the application's classes are loaded again by a new class loader on each restart, so their static fields start from scratch, while static state in libraries survives.generation
A restart still runs all of the application's own startup: bean creation, database migrations, cache warm-up. If that part is slow, a restart is slow too. Lazy initialisation with spring.main.lazy-initialization=true
Two class loaders, and the ClassCastException they cause
The restart class loader is the reason restarts work, and also the source of DevTools' best-known error: X cannot be cast to XURLClassLoader
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import javax.tools.ToolProvider;
public class TwoClassLoaders {
/** Lives in the base class loader, like a library jar: survives every restart. */
public static final Map<String, Object> CACHE = new HashMap<>();
/** Writes and compiles the "application" class, as an IDE does on save. */
static void compile(Path dir, String greeting) throws Exception {
Path source = dir.resolve("Greeter.java");
Files.writeString(source, """
public class Greeter implements java.util.function.Supplier<String> {
public String get() {
return "%s";
}
}
""".formatted(greeting));
int result = ToolProvider.getSystemJavaCompiler().run(null, null, null,
"-cp", System.getProperty("java.class.path"), "-d", dir.toString(),
source.toString());
if (result != 0) {
throw new IllegalStateException("compile failed");
}
}
/** A new restart class loader for each run of the application. */
@SuppressWarnings("unchecked")
static Supplier<String> startApplication(Path dir, int run) throws Exception {
URLClassLoader restartLoader = new URLClassLoader("restart-" + run,
new URL[] {dir.toUri().toURL()}, TwoClassLoaders.class.getClassLoader());
Class<?> greeterClass = restartLoader.loadClass("Greeter");
Supplier<String> greeter =
(Supplier<String>) greeterClass.getDeclaredConstructor().newInstance();
System.out.println(" run " + run + ": " + greeter.get() + " (class loaded by "
+ greeterClass.getClassLoader().getName() + ")");
return greeter;
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("restart");
System.out.println("Base class loader holds TwoClassLoaders and the JDK; "
+ "a restart loader holds Greeter.");
compile(dir, "Hello");
Supplier<String> first = startApplication(dir, 1);
CACHE.put("greeter", first);
System.out.println("Source edited and recompiled, application restarted:");
compile(dir, "Hello, edited without restarting the JVM");
Supplier<String> second = startApplication(dir, 2);
System.out.println("Same class name, same class? "
+ (first.getClass() == second.getClass()));
Object cached = CACHE.get("greeter");
System.out.println("Object cached during run 1 is a run-2 Greeter? "
+ second.getClass().isInstance(cached));
try {
Object cast = second.getClass().cast(cached);
System.out.println(" cast worked: " + cast);
} catch (ClassCastException e) {
System.out.println(" ClassCastException: " + e.getMessage());
}
}
}
Base class loader holds TwoClassLoaders and the JDK; a restart loader holds Greeter.
run 1: Hello (class loaded by restart-1)
Source edited and recompiled, application restarted:
run 2: Hello, edited without restarting the JVM (class loaded by restart-2)
Same class name, same class? false
Object cached during run 1 is a run-2 Greeter? false
ClassCastException: Cannot cast Greeter to Greeter
- Run 1 printed
, from aHello loaded byGreeter . After the edit, run 2 printed the new text from a class loaded byrestart-1 , without restarting the JVM.restart-2 - The two
classes have the same name but are different classes: a class's identity is its name together with the class loader that defined it.Greeter - The object cached in the base loader during run 1 is not an instance of run 2's
, and casting it failed withGreeter .Cannot cast Greeter to Greeter
The same happens when a library in the base loader keeps application objects across a restart: an in-memory cache, a session store, a static registry. The fix is to move the library into the restart class loader, or to stop it from keeping objects across restarts. A META-INF/spring-devtools.propertiesrestart.include.*restart.exclude.*
restart.exclude.companycommonlibs=/mycorp-common-[\\w\\d-\\.]/(build|bin|out|target)/
restart.include.projectcommon=/mycorp-myproj-[\\w\\d-\\.]+\\.jar
Deserialization after a restart
Session persistence, caches written to disk and some messaging libraries deserialize objects with Java serialization. A cart item serialized from the restart class loader is read back here in two ways:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.tools.ToolProvider;
import org.springframework.core.ConfigurableObjectInputStream;
public class DeserializationTrap {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("restart");
Path source = dir.resolve("CartItem.java");
Files.writeString(source, """
public class CartItem implements java.io.Serializable {
private static final long serialVersionUID = 1L;
String sku = "BOOK-7";
public String toString() {
return "CartItem[" + sku + "]";
}
}
""");
ToolProvider.getSystemJavaCompiler().run(null, null, null,
"-d", dir.toString(), source.toString());
ClassLoader restartLoader = new URLClassLoader("restart",
new URL[] {dir.toUri().toURL()}, DeserializationTrap.class.getClassLoader());
Object item = restartLoader.loadClass("CartItem").getDeclaredConstructor().newInstance();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(item);
}
System.out.println("Serialized " + item + " from the restart class loader, "
+ bytes.size() + " bytes");
Thread.currentThread().setContextClassLoader(restartLoader);
System.out.println("1. Plain ObjectInputStream:");
try (ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()))) {
System.out.println(" read " + in.readObject());
} catch (ClassNotFoundException e) {
System.out.println(" ClassNotFoundException: " + e.getMessage());
}
System.out.println("2. ConfigurableObjectInputStream with the context class loader:");
try (ObjectInputStream in = new ConfigurableObjectInputStream(
new ByteArrayInputStream(bytes.toByteArray()),
Thread.currentThread().getContextClassLoader())) {
System.out.println(" read " + in.readObject());
}
}
}
Serialized CartItem[BOOK-7] from the restart class loader, 65 bytes
1. Plain ObjectInputStream:
ClassNotFoundException: CartItem
2. ConfigurableObjectInputStream with the context class loader:
read CartItem[BOOK-7]
- The plain
failed withObjectInputStream , even though the thread's context class loader was set to the restart loader. It resolves classes through the loader of the code that calls it, here the base loader, which cannot see the application's classes.ClassNotFoundException: CartItem - Spring's
, givenConfigurableObjectInputStream , found the class and readThread.currentThread().getContextClassLoader() .CartItem[BOOK-7]
This is the workaround the DevTools documentation gives for restart problems with deserialization. Libraries that deserialize without consulting the context class loader fail in the same way, and the documentation's advice is to ask their authors for a fix. DevTools sets server.servlet.session.persistent=true
Configuring restart and the development defaults
Not every change should restart the application. Static resources and templates do not need it, and some projects want restarts only on demand:
| Property | Effect |
|---|---|
spring.devtools.restart.exclude | Replaces the default exclusions: /META-INF/maven/META-INF/resources/resources/static/public/templates |
spring.devtools.restart.additional-exclude | Adds exclusions and keeps the defaults |
spring.devtools.restart.additional-paths | Watches extra paths outside the classpath |
spring.devtools.restart.trigger-file | Checks for changes only when this file changes, so a series of edits causes one restart |
spring.devtools.restart.poll-intervalquiet-period | How often to check for changes, and how long no change must be seen before restarting |
Raise the poll interval and quiet period, for example to 2s1sMETA-INF/spring-devtools.propertiesdefaults.
,spring.thymeleaf.cache andspring.freemarker.cache set tospring.mustache.servlet.cache , andfalse , so edits are served at once.spring.web.resources.cache.period=0 ,spring.web.error.include-message andinclude-binding-errors set toinclude-stacktrace , so error pages show full detail.always andspring.mvc.log-resolved-exception=true , both seen in the restart example above.server.servlet.session.persistent=true ,spring.h2.console.enabled=true andspring.graphql.graphiql.enabled=true , from the H2 console, GraphQL and Micrometer Tracing modules.management.tracing.sampling.probability=1.0
spring.devtools.add-properties=false
Remote DevTools, LiveReload and alternatives
- Remote DevTools: with
set and DevTools packaged into the jar, a local client can push class changes to an application running elsewhere. The documentation calls this a security risk, to be used only on a trusted network or over SSL and never on a production deployment.spring.devtools.remote.secret - LiveReload: DevTools still starts a LiveReload server that browser extensions use to refresh the page, but it is deprecated since Spring Boot 4.1.0 without a replacement. Front-end tooling with its own dev server is the usual alternative.
- Debugger HotSwap: running under the IDE debugger, the JVM can replace method bodies in place without any restart. It cannot add fields or methods, but for small edits it is faster than a restart.
- Class reloading tools: JRebel rewrites classes so that most changes reload without a restart. With JRebel active, DevTools disables its own restart and keeps the other features.
- Development services:
or Testcontainers at development time start databases and brokers for the application. Thespring-boot-docker-composeDocker page shows the Compose setup.
Choosing a development loop
| Need | Use |
|---|---|
| See code changes without a full restart | DevTools automatic restart |
| Template and static file edits | DevTools' cache-off defaults, no restart needed |
| Small method-body edits while debugging | The IDE debugger's HotSwap |
| Fewer restarts during a burst of edits | spring.devtools.restart.trigger-file |
X cannot be cast to X | restart.includerestart.excludeMETA-INF/spring-devtools.properties |
| Deserializing application classes | ConfigurableObjectInputStream |
| Changes reloaded without restarts at all | A class reloading agent such as JRebel |
| Databases and brokers on the developer's machine | spring-boot-docker-compose |
DevTools is worth adding to every Spring Boot project: it costs nothing in production, where it disables itself and is left out of the jar. The