此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Boot 3.4.3! |
开发人员工具
Spring Boot 包含一组额外的工具,这些工具可以使应用程序开发体验更加愉快。
这spring-boot-devtools
module 可以包含在任何项目中,以提供额外的开发时功能。
要包含 devtools 支持,请将模块依赖项添加到您的构建中,如以下 Maven 和 Gradle 清单所示:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
dependencies {
developmentOnly("org.springframework.boot:spring-boot-devtools")
}
Devtools 可能会导致类加载问题,尤其是在多模块项目中。诊断类加载问题 介绍了如何诊断和解决这些问题。 |
在运行完全打包的应用程序时,会自动禁用开发人员工具。
如果您的应用程序是从java -jar 或者,如果它是从特殊的 Classloader 启动的,则将其视为 “production application”。
您可以使用spring.devtools.restart.enabled system 属性。
要启用 devtools,无论使用哪种类加载器来启动应用程序,都可以将-Dspring.devtools.restart.enabled=true system 属性。
在运行 devtools 存在安全风险的生产环境中,不得执行此作。
要禁用 devtools,请排除依赖项或将-Dspring.devtools.restart.enabled=false system 属性。 |
在 Maven 中将依赖项标记为可选,或使用developmentOnly 配置(如上所示)可防止 devtools 被传递到使用您项目的其他模块。 |
默认情况下,重新打包的存档不包含 devtools。
如果你想使用某个远程 devtools 功能,你需要包含它。
使用 Maven 插件时,将excludeDevtools property 设置为false .
使用 Gradle 插件时,配置任务的 Classpath 以包含developmentOnly 配置. |
诊断类加载问题
如 Restart vs Reload 部分所述,重新启动功能是使用两个类加载器实现的。 对于大多数应用程序,此方法效果很好。 但是,它有时会导致类加载问题,尤其是在多模块项目中。
要诊断类加载问题是否确实是由 devtools 及其两个类加载器引起的,请尝试禁用 restart。 如果这解决了您的问题,请自定义重新启动类加载器以包含整个项目。
属性默认值
Spring Boot 支持的几个库使用缓存来提高性能。 例如,模板引擎会缓存已编译的模板,以避免重复解析模板文件。 此外,Spring MVC 可以在提供静态资源时将 HTTP 缓存头添加到响应中。
虽然缓存在生产中非常有益,但在开发过程中可能会适得其反,阻止您看到刚刚在应用程序中所做的更改。 因此,spring-boot-devtools默认禁用缓存选项。
缓存选项通常由application.properties
文件。
例如,Thymeleaf 提供了spring.thymeleaf.cache
财产。
无需手动设置这些属性,spring-boot-devtools
module 会自动应用合理的开发时配置。
下表列出了应用的所有属性:
名字 | 默认值 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
如果不希望应用属性默认值,则可以设置spring.devtools.add-properties 自false 在application.properties . |
由于在开发 Spring MVC 和 Spring WebFlux 应用程序时需要有关 Web 请求的更多信息,因此开发人员工具建议您启用DEBUG
logging 的web
logging 组。
这将为您提供有关传入请求、哪个处理程序正在处理该请求、响应结果和其他详细信息的信息。
如果您希望记录所有请求详细信息(包括潜在的敏感信息),您可以打开spring.mvc.log-request-details
或spring.codec.log-request-details
configuration 属性。
自动重启
使用spring-boot-devtools
每当 Classpath 上的文件发生更改时自动重新启动。
在 IDE 中工作时,这可能是一个有用的功能,因为它为代码更改提供了一个非常快速的反馈循环。
默认情况下,将监视 Classpath 上指向目录的任何条目的更改。
请注意,某些资源(如静态资产和视图模板)不需要重新启动应用程序。
如果您使用构建插件通过 Maven 或 Gradle 重新启动,则必须将forking 设置为enabled .
如果禁用 forking,则不会创建 devtools 使用的隔离应用程序类加载器,并且重启将无法正常运行。 |
与 LiveReload 一起使用时,自动重启效果非常好。 有关详细信息,请参阅 LiveReload 部分。 如果使用 JRebel,则禁用自动重启,以支持动态类重新加载。 其他 devtools 功能(例如 LiveReload 和属性覆盖)仍然可以使用。 |
DevTools 依赖于应用程序上下文的 shutdown 钩子在重启期间关闭它。
如果您禁用了 shutdown hook (SpringApplication.setRegisterShutdownHook(false) ). |
DevTools 需要自定义ResourceLoader 由ApplicationContext .
如果您的应用程序已经提供了一个,那么它将被包装。
直接覆盖getResource 方法上的ApplicationContext 不支持。 |
使用 AspectJ 编织时不支持自动重启。 |
在条件评估中记录变化
默认情况下,每次应用程序重新启动时,都会记录一个显示条件评估增量的报告。 该报告显示在您进行更改(例如添加或删除 Bean 以及设置配置属性)时对应用程序的自动配置的更改。
要禁用报表的日志记录,请设置以下属性:
-
Properties
-
YAML
spring.devtools.restart.log-condition-evaluation-delta=false
spring:
devtools:
restart:
log-condition-evaluation-delta: false
排除资源
某些资源在更改时不一定需要触发重启。
例如,可以就地编辑 Thymeleaf 模板。
默认情况下,将/META-INF/maven
,/META-INF/resources
,/resources
,/static
,/public
或/templates
不会触发重新启动,但会触发实时重新加载。
如果要自定义这些排除项,可以使用spring.devtools.restart.exclude
财产。
例如,要仅排除/static
和/public
您将设置以下属性:
-
Properties
-
YAML
spring.devtools.restart.exclude=static/**,public/**
spring:
devtools:
restart:
exclude: "static/**,public/**"
如果要保留这些默认值并添加其他排除项,请使用spring.devtools.restart.additional-exclude property 来代替。 |
禁用重启
如果您不想使用重启功能,可以使用spring.devtools.restart.enabled
财产。
在大多数情况下,您可以在application.properties
(这样做仍然会初始化 Restart ClassLoader,但它不会监视文件更改)。
如果需要完全禁用重启支持(例如,因为它不适用于特定库),则需要将spring.devtools.restart.enabled
System
property 设置为false
在调用SpringApplication.run(…)
,如以下示例所示:
-
Java
-
Kotlin
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(MyApplication.class, args);
}
}
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
object MyApplication {
@JvmStatic
fun main(args: Array<String>) {
System.setProperty("spring.devtools.restart.enabled", "false")
SpringApplication.run(MyApplication::class.java, *args)
}
}
Using a Trigger File
If you work with an IDE that continuously compiles changed files, you might prefer to trigger restarts only at specific times.
To do so, you can use a “trigger file”, which is a special file that must be modified when you want to actually trigger a restart check.
Any update to the file will trigger a check, but restart only actually occurs if Devtools has detected it has something to do.
To use a trigger file, set the spring.devtools.restart.trigger-file
property to the name (excluding any path) of your trigger file.
The trigger file must appear somewhere on your classpath.
For example, if you have a project with the following structure:
src
+- main
+- resources
+- .reloadtrigger
Then your trigger-file
property would be:
-
Properties
-
YAML
spring.devtools.restart.trigger-file=.reloadtrigger
spring:
devtools:
restart:
trigger-file: ".reloadtrigger"
Restarts will now only happen when the src/main/resources/.reloadtrigger
is updated.
You might want to set spring.devtools.restart.trigger-file
as a global setting, so that all your projects behave in the same way.
Some IDEs have features that save you from needing to update your trigger file manually.
Spring Tools for Eclipse and IntelliJ IDEA (Ultimate Edition) both have such support.
With Spring Tools, you can use the “reload” button from the console view (as long as your trigger-file
is named .reloadtrigger
).
For IntelliJ IDEA, you can follow the instructions in their documentation.
Customizing the Restart Classloader
As described earlier in the Restart vs Reload section, restart functionality is implemented by using two classloaders.
If this causes issues, you can diagnose the problem by using the spring.devtools.restart.enabled
system property, and if the app works with restart switched off, you might need to customize what gets loaded by which classloader.
By default, any open project in your IDE is loaded with the “restart” classloader, and any regular .jar
file is loaded with the “base” classloader.
The same is true if you use mvn spring-boot:run
or gradle bootRun
: the project containing your @SpringBootApplication
is loaded with the “restart” classloader, and everything else with the “base” classloader.
The classpath is printed on the console when you start the app, which can help to identify any problematic entries.
Classes used reflectively, especially annotations, can be loaded into the parent (fixed) classloader on startup before the application classes which use them, and this might lead to them not being detected by Spring in the application.
You can instruct Spring Boot to load parts of your project with a different classloader by creating a META-INF/spring-devtools.properties
file.
The spring-devtools.properties
file can contain properties prefixed with restart.exclude
and restart.include
.
The include
elements are items that should be pulled up into the “restart” classloader, and the exclude
elements are items that should be pushed down into the “base” classloader.
The value of the property is a regex pattern that is applied to the classpath passed to the JVM on startup.
Here is an example where some local class files are excluded and some extra libraries are included in the restart class loader:
restart:
exclude:
companycommonlibs: "/mycorp-common-[\\w\\d-\\.]/(build|bin|out|target)/"
include:
projectcommon: "/mycorp-myproj-[\\w\\d-\\.]+\\.jar"
All property keys must be unique.
As long as a property starts with restart.include.
or restart.exclude.
it is considered.
All META-INF/spring-devtools.properties
from the classpath are loaded.
You can package files inside your project, or in the libraries that the project consumes.
System properties can not be used, only the properties file.
Known Limitations
Restart functionality does not work well with objects that are deserialized by using a standard ObjectInputStream
.
If you need to deserialize data, you may need to use Spring’s ConfigurableObjectInputStream
in combination with Thread.currentThread().getContextClassLoader()
.
Unfortunately, several third-party libraries deserialize without considering the context classloader.
If you find such a problem, you need to request a fix with the original authors.
LiveReload
The spring-boot-devtools
module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed.
LiveReload browser extensions are freely available for Chrome, Firefox and Safari.
You can find these extensions by searching 'LiveReload' in the marketplace or store of your chosen browser.
If you do not want to start the LiveReload server when your application runs, you can set the spring.devtools.livereload.enabled
property to false
.
You can only run one LiveReload server at a time.
Before starting your application, ensure that no other LiveReload servers are running.
If you start multiple applications from your IDE, only the first has LiveReload support.
To trigger LiveReload when a file changes, Automatic Restart must be enabled.
Global Settings
You can configure global devtools settings by adding any of the following files to the $HOME/.config/spring-boot
directory:
-
spring-boot-devtools.properties
-
spring-boot-devtools.yaml
-
spring-boot-devtools.yml
Any properties added to these files apply to all Spring Boot applications on your machine that use devtools.
For example, to configure restart to always use a trigger file, you would add the following property to your spring-boot-devtools
file:
-
Properties
-
YAML
spring.devtools.restart.trigger-file=.reloadtrigger
spring:
devtools:
restart:
trigger-file: ".reloadtrigger"
By default, $HOME
is the user’s home directory.
To customize this location, set the SPRING_DEVTOOLS_HOME
environment variable or the spring.devtools.home
system property.
If devtools configuration files are not found in $HOME/.config/spring-boot
, the root of the $HOME
directory is searched for the presence of a .spring-boot-devtools.properties
file.
This allows you to share the devtools global configuration with applications that are on an older version of Spring Boot that does not support the $HOME/.config/spring-boot
location.
Profiles are not supported in devtools properties/yaml files.
Any profiles activated in .spring-boot-devtools.properties
will not affect the loading of profile-specific configuration files.
Profile specific filenames (of the form spring-boot-devtools-<profile>.properties
) and spring.config.activate.on-profile
documents in both YAML and Properties files are not supported.
Configuring File System Watcher
FileSystemWatcher
works by polling the class changes with a certain time interval, and then waiting for a predefined quiet period to make sure there are no more changes.
Since Spring Boot relies entirely on the IDE to compile and copy files into the location from where Spring Boot can read them, you might find that there are times when certain changes are not reflected when devtools restarts the application.
If you observe such problems constantly, try increasing the spring.devtools.restart.poll-interval
and spring.devtools.restart.quiet-period
parameters to the values that fit your development environment:
-
Properties
-
YAML
spring.devtools.restart.poll-interval=2s
spring.devtools.restart.quiet-period=1s
spring:
devtools:
restart:
poll-interval: "2s"
quiet-period: "1s"
The monitored classpath directories are now polled every 2 seconds for changes, and a 1 second quiet period is maintained to make sure there are no additional class changes.
Remote Applications
The Spring Boot developer tools are not limited to local development.
You can also use several features when running applications remotely.
Remote support is opt-in as enabling it can be a security risk.
It should only be enabled when running on a trusted network or when secured with SSL.
If neither of these options is available to you, you should not use DevTools' remote support.
You should never enable support on a production deployment.
To enable it, you need to make sure that devtools
is included in the repackaged archive, as shown in the following listing:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludeDevtools>false</excludeDevtools>
</configuration>
</plugin>
</plugins>
</build>
Then you need to set the spring.devtools.remote.secret
property.
Like any important password or secret, the value should be unique and strong such that it cannot be guessed or brute-forced.
Remote devtools support is provided in two parts: a server-side endpoint that accepts connections and a client application that you run in your IDE.
The server component is automatically enabled when the spring.devtools.remote.secret
property is set.
The client component must be launched manually.
Remote devtools is not supported for Spring WebFlux applications.
Running the Remote Client Application
The remote client application is designed to be run from within your IDE.
You need to run RemoteSpringApplication
with the same classpath as the remote project that you connect to.
The application’s single required argument is the remote URL to which it connects.
For example, if you are using Eclipse or Spring Tools and you have a project named my-app
that you have deployed to Cloud Foundry, you would do the following:
-
Select Run Configurations…
from the Run
menu.
-
Create a new Java Application
“launch configuration”.
-
Browse for the my-app
project.
-
Use RemoteSpringApplication
as the main class.
-
Add https://myapp.cfapps.io
to the Program arguments
(or whatever your remote URL is).
A running remote client might resemble the following listing:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \
\\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) )
' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / /
=========|_|==============|___/===================================/_/_/_/
:: Spring Boot Remote :: (v3.5.0-SNAPSHOT)
2025-03-15T00:32:39.814Z INFO 89870 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication v3.5.0-SNAPSHOT using Java 17.0.14 with PID 89870 (/Users/myuser/.m2/repository/org/springframework/boot/spring-boot-devtools/3.5.0-SNAPSHOT/spring-boot-devtools-3.5.0-SNAPSHOT.jar started by myuser in /opt/apps/)
2025-03-15T00:32:39.821Z INFO 89870 --- [ main] o.s.b.devtools.RemoteSpringApplication : No active profile set, falling back to 1 default profile: "default"
2025-03-15T00:32:40.371Z INFO 89870 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2025-03-15T00:32:40.423Z INFO 89870 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 1.9 seconds (process running for 2.775)
Because the remote client is using the same classpath as the real application it can directly read application properties.
This is how the spring.devtools.remote.secret
property is read and passed to the server for authentication.
It is always advisable to use https://
as the connection protocol, so that traffic is encrypted and passwords cannot be intercepted.
If you need to use a proxy to access the remote application, configure the spring.devtools.remote.proxy.host
and spring.devtools.remote.proxy.port
properties.
Remote Update
The remote client monitors your application classpath for changes in the same way as the local restart.
Any updated resource is pushed to the remote application and (if required) triggers a restart.
This can be helpful if you iterate on a feature that uses a cloud service that you do not have locally.
Generally, remote updates and restarts are much quicker than a full rebuild and deploy cycle.
On a slower development environment, it may happen that the quiet period is not enough, and the changes in the classes may be split into batches.
The server is restarted after the first batch of class changes is uploaded.
The next batch can’t be sent to the application, since the server is restarting.
This is typically manifested by a warning in the RemoteSpringApplication
logs about failing to upload some of the classes, and a consequent retry.
But it may also lead to application code inconsistency and failure to restart after the first batch of changes is uploaded.
If you observe such problems constantly, try increasing the spring.devtools.restart.poll-interval
and spring.devtools.restart.quiet-period
parameters to the values that fit your development environment.
See the Configuring File System Watcher section for configuring these properties.
Files are only monitored when the remote client is running.
If you change a file before starting the remote client, it is not pushed to the remote server.