使用 Spring Boot
1. 构建系统
强烈建议您选择支持依赖项管理并且可以使用发布到 “Maven Central” 存储库的工件的构建系统。 我们建议您选择 Maven 或 Gradle。 可以让 Spring Boot 与其他构建系统(例如 Ant)一起使用,但它们没有得到特别好的支持。
1.1. 依赖管理
Spring Boot 的每个版本都提供了它支持的依赖项的精选列表。 实际上,你不需要在构建配置中为这些依赖项中的任何一个提供版本,因为 Spring Boot 会为你管理。 当您升级 Spring Boot 本身时,这些依赖项也会以一致的方式升级。
如果需要,您仍然可以指定版本并覆盖 Spring Boot 的建议。 |
精选列表包含可与 Spring Boot 一起使用的所有 Spring 模块,以及第三方库的精炼列表。
该列表作为标准物料清单 (spring-boot-dependencies
),该 McD 的 Git。
Spring Boot 的每个版本都与 Spring Framework 的基本版本相关联。 我们强烈建议您不要指定其版本。 |
1.4. Ant
可以使用 Apache Ant+Ivy 构建 Spring Boot 项目。
这spring-boot-antlib
“AntLib” 模块也可用于帮助 Ant 创建可执行的 jar。
要声明依赖项,典型的ivy.xml
file 类似于以下示例:
<ivy-module version="2.0">
<info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
<configurations>
<conf name="compile" description="everything needed to compile this module" />
<conf name="runtime" extends="compile" description="everything needed to run this module" />
</configurations>
<dependencies>
<dependency org="org.springframework.boot" name="spring-boot-starter"
rev="${spring-boot.version}" conf="compile" />
</dependencies>
</ivy-module>
典型的build.xml
如以下示例所示:
<project
xmlns:ivy="antlib:org.apache.ivy.ant"
xmlns:spring-boot="antlib:org.springframework.boot.ant"
name="myapp" default="build">
<property name="spring-boot.version" value="3.0.13" />
<target name="resolve" description="--> retrieve dependencies with ivy">
<ivy:retrieve pattern="lib/[conf]/[artifact]-[type]-[revision].[ext]" />
</target>
<target name="classpaths" depends="resolve">
<path id="compile.classpath">
<fileset dir="lib/compile" includes="*.jar" />
</path>
</target>
<target name="init" depends="classpaths">
<mkdir dir="build/classes" />
</target>
<target name="compile" depends="init" description="compile">
<javac srcdir="src/main/java" destdir="build/classes" classpathref="compile.classpath" />
</target>
<target name="build" depends="compile">
<spring-boot:exejar destfile="build/myapp.jar" classes="build/classes">
<spring-boot:lib>
<fileset dir="lib/runtime" />
</spring-boot:lib>
</spring-boot:exejar>
</target>
</project>
如果您不想使用spring-boot-antlib 模块中,请参阅 howto.html “How-to” 。 |
1.5. Starters
Starters 是一组方便的依赖项描述符,您可以将其包含在应用程序中。
您可以获得所需的所有 Spring 和相关技术的一站式商店,而无需搜索示例代码和复制粘贴依赖项描述符。
例如,如果您想开始使用 Spring 和 JPA 进行数据库访问,请包括spring-boot-starter-data-jpa
依赖项。
Starter 包含许多依赖项,您需要这些依赖项才能快速启动和运行项目,并具有一组一致、受支持的托管传递依赖项。
Spring Boot 在org.springframework.boot
群:
名字 | 描述 |
---|---|
核心Starters,包括自动配置支持、日志记录和 YAML |
|
使用 Spring AMQP 和 Rabbit MQ 的入门 |
|
使用 Spring AOP 和 AspectJ 进行面向方面编程的入门 |
|
使用 Apache Artemis 的 Starter for JMS 消息传递 |
|
使用 Spring Batch 的 Starter |
|
使用 Spring Framework 的缓存支持的 Starter |
|
使用 Cassandra 分布式数据库和 Spring Data Cassandra 的入门 |
|
使用 Cassandra 分布式数据库和 Spring Data Cassandra Reactive 的入门 |
|
使用 Couchbase 面向文档的数据库和 Spring Data Couchbase 的入门 |
|
使用 Couchbase 面向文档的数据库和 Spring Data Couchbase Reactive 的入门 |
|
使用 Elasticsearch 搜索和分析引擎和 Spring Data Elasticsearch 的入门版 |
|
使用 Spring Data JDBC 的初学者 |
|
将 Spring Data JPA 与 Hibernate 结合使用的入门 |
|
使用 Spring Data LDAP 的入门 |
|
使用 MongoDB 面向文档的数据库和 Spring Data MongoDB 的入门 |
|
使用 MongoDB 面向文档的数据库和 Spring Data MongoDB Reactive 的入门 |
|
使用 Neo4j 图形数据库和 Spring Data Neo4j 的入门 |
|
使用 Spring Data R2DBC 的Starters |
|
将 Redis 键值数据存储与 Spring Data Redis 和 Lettuce 客户端结合使用的入门 |
|
将 Redis 键值数据存储与 Spring Data Redis 反应式和 Lettuce 客户端一起使用的入门 |
|
使用 Spring Data REST 和 Spring MVC 通过 REST 公开 Spring Data 存储库的入门 |
|
使用 FreeMarker 视图构建 MVC Web 应用程序的入门 |
|
使用 Spring GraphQL 构建 GraphQL 应用程序的入门 |
|
使用 Groovy Templates 视图构建 MVC Web 应用程序的 Starter |
|
使用 Spring MVC 和 Spring HATEOAS 构建基于超媒体的 RESTful Web 应用程序的入门 |
|
使用 Spring 集成的 Starter |
|
将 JDBC 与 HikariCP 连接池一起使用的入门 |
|
使用 JAX-RS 和 Jersey 构建 RESTful Web 应用程序的入门工具。替代 |
|
使用 jOOQ 通过 JDBC 访问 SQL 数据库的入门工具。替代 |
|
用于读取和写入 json 的 Starter |
|
使用 Java Mail 和 Spring Framework 的电子邮件发送支持的入门 |
|
使用 Mustache 视图构建 Web 应用程序的入门 |
|
使用 Spring Security 的 OAuth2/OpenID Connect 客户端功能的入门 |
|
使用 Spring Security 的 OAuth2 资源服务器功能的入门 |
|
使用 Quartz 调度程序的入门 |
|
用于构建 RSocket 客户端和服务器的 Starter |
|
使用 Spring Security 的 Starter |
|
用于使用 JUnit Jupiter、Hamcrest 和 Mockito 等库测试 Spring Boot 应用程序的 Starter |
|
使用 Thymeleaf 视图构建 MVC Web 应用程序的入门 |
|
将 Java Bean 验证与 Hibernate 验证器结合使用的入门 |
|
使用 Spring MVC 构建 Web(包括 RESTful)应用程序的入门工具。使用 Tomcat 作为默认嵌入式容器 |
|
使用 Spring Web 服务的入门 |
|
使用 Spring Framework 的反应式 Web 支持构建 WebFlux 应用程序的入门 |
|
使用 Spring Framework 的 MVC WebSocket 支持构建 WebSocket 应用程序的入门工具 |
除了应用程序Starters之外,以下Starters还可用于添加生产就绪功能:
名字 | 描述 |
---|---|
使用 Spring Boot 的 Actuator 的 Starter,它提供生产就绪功能来帮助您监控和管理应用程序 |
最后,Spring Boot 还包括以下Starters,如果你想排除或交换特定的技术方面,可以使用这些Starters:
名字 | 描述 |
---|---|
使用 Jetty 作为嵌入式 servlet 容器的入门工具。替代 |
|
使用 Log4j2 进行日志记录的入门。替代 |
|
使用 Logback 进行日志记录的Starters。默认日志记录Starters |
|
使用 Reactor Netty 作为嵌入式反应式 HTTP 服务器的入门。 |
|
使用 Tomcat 作为嵌入式 servlet 容器的入门工具。默认 servlet 容器Starters由 |
|
使用 Undertow 作为嵌入式 servlet 容器的入门工具。替代 |
要了解如何交换技术方面,请参阅交换 Web 服务器和日志记录系统的作文档。
2. 构建代码
Spring Boot 不需要任何特定的代码布局即可工作。 但是,有一些最佳实践会有所帮助。
2.1. 使用 “default” 软件包
当类不包含package
声明,则认为它位于 “default package” 中。
通常不建议使用 “default package” 并且应该避免使用。
它可能会导致使用@ComponentScan
,@ConfigurationPropertiesScan
,@EntityScan
或@SpringBootApplication
注解,因为每个 jar 中的每个类都会被读取。
我们建议您遵循 Java 建议的包命名约定,并使用反向域名(例如com.example.project ). |
2.2. 找到 Main Application 类
我们通常建议您将主应用程序类放在其他类上方的根包中。
这@SpringBootApplication
注解通常放在你的主类上,它隐式地定义了某些项目的基本 “搜索包”。
例如,如果您正在编写 JPA 应用程序,则@SpringBootApplication
annotated 类用于搜索@Entity
项目。
使用根包还允许组件扫描仅应用于您的项目。
如果您不想使用@SpringBootApplication 这@EnableAutoConfiguration 和@ComponentScan 它导入的 annotations 定义了该行为,因此您也可以改用这些 Comments。 |
下面的清单显示了一个典型的布局:
com +- example +- myapplication +- MyApplication.java | +- customer | +- Customer.java | +- CustomerController.java | +- CustomerService.java | +- CustomerRepository.java | +- order +- Order.java +- OrderController.java +- OrderService.java +- OrderRepository.java
这MyApplication.java
file 将声明main
方法以及基本@SpringBootApplication
如下:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Kotlin
@SpringBootApplication
class MyApplication
fun main(args: Array<String>) {
runApplication<MyApplication>(*args)
}
3. Configuration Classes
Spring Boot favors Java-based configuration.
Although it is possible to use SpringApplication
with XML sources, we generally recommend that your primary source be a single @Configuration
class.
Usually the class that defines the main
method is a good candidate as the primary @Configuration
.
Many Spring configuration examples have been published on the Internet that use XML configuration.
If possible, always try to use the equivalent Java-based configuration.
Searching for Enable*
annotations can be a good starting point.
3.1. Importing Additional Configuration Classes
You need not put all your @Configuration
into a single class.
The @Import
annotation can be used to import additional configuration classes.
Alternatively, you can use @ComponentScan
to automatically pick up all Spring components, including @Configuration
classes.
4. Auto-configuration
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.
For example, if HSQLDB
is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.
You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration
or @SpringBootApplication
annotations to one of your @Configuration
classes.
You should only ever add one @SpringBootApplication
or @EnableAutoConfiguration
annotation.
We generally recommend that you add one or the other to your primary @Configuration
class only.
4.1. Gradually Replacing Auto-configuration
Auto-configuration is non-invasive.
At any point, you can start to define your own configuration to replace specific parts of the auto-configuration.
For example, if you add your own DataSource
bean, the default embedded database support backs away.
If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug
switch.
Doing so enables debug logs for a selection of core loggers and logs a conditions report to the console.
4.2. Disabling Specific Auto-configuration Classes
If you find that specific auto-configuration classes that you do not want are being applied, you can use the exclude attribute of @SpringBootApplication
to disable them, as shown in the following example:
Java
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class MyApplication {
}
Kotlin
@SpringBootApplication(exclude = [DataSourceAutoConfiguration::class])
class MyApplication
If the class is not on the classpath, you can use the excludeName
attribute of the annotation and specify the fully qualified name instead.
If you prefer to use @EnableAutoConfiguration
rather than @SpringBootApplication
, exclude
and excludeName
are also available.
Finally, you can also control the list of auto-configuration classes to exclude by using the spring.autoconfigure.exclude
property.
You can define exclusions both at the annotation level and by using the property.
Even though auto-configuration classes are public
, the only aspect of the class that is considered public API is the name of the class which can be used for disabling the auto-configuration.
The actual contents of those classes, such as nested configuration classes or bean methods are for internal use only and we do not recommend using those directly.
4.3. Auto-configuration Packages
Auto-configuration packages are the packages that various auto-configured features look in by default when scanning for things such as entities and Spring Data repositories.
The @EnableAutoConfiguration
annotation (either directly or through its presence on @SpringBootApplication
) determines the default auto-configuration package.
Additional packages can be configured using the @AutoConfigurationPackage
annotation.
5. Spring Beans and Dependency Injection
You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies.
We generally recommend using constructor injection to wire up dependencies and @ComponentScan
to find beans.
If you structure your code as suggested above (locating your application class in a top package), you can add @ComponentScan
without any arguments or use the @SpringBootApplication
annotation which implicitly includes it.
All of your application components (@Component
, @Service
, @Repository
, @Controller
, and others) are automatically registered as Spring Beans.
The following example shows a @Service
Bean that uses constructor injection to obtain a required RiskAssessor
bean:
Java
@Service
public class MyAccountService implements AccountService {
private final RiskAssessor riskAssessor;
public MyAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
Kotlin
@Service
class MyAccountService(private val riskAssessor: RiskAssessor) : AccountService
If a bean has more than one constructor, you will need to mark the one you want Spring to use with @Autowired
:
Java
@Service
public class MyAccountService implements AccountService {
private final RiskAssessor riskAssessor;
private final PrintStream out;
@Autowired
public MyAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
this.out = System.out;
}
public MyAccountService(RiskAssessor riskAssessor, PrintStream out) {
this.riskAssessor = riskAssessor;
this.out = out;
}
// ...
}
Kotlin
@Service
class MyAccountService : AccountService {
private val riskAssessor: RiskAssessor
private val out: PrintStream
@Autowired
constructor(riskAssessor: RiskAssessor) {
this.riskAssessor = riskAssessor
out = System.out
}
constructor(riskAssessor: RiskAssessor, out: PrintStream) {
this.riskAssessor = riskAssessor
this.out = out
}
// ...
}
Notice how using constructor injection lets the riskAssessor
field be marked as final
, indicating that it cannot be subsequently changed.
6. Using the @SpringBootApplication Annotation
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class".
A single @SpringBootApplication
annotation can be used to enable those three features, that is:
-
@EnableAutoConfiguration
: enable Spring Boot’s auto-configuration mechanism
-
@ComponentScan
: enable @Component
scan on the package where the application is located (see the best practices)
-
@SpringBootConfiguration
: enable registration of extra beans in the context or the import of additional configuration classes.
An alternative to Spring’s standard @Configuration
that aids configuration detection in your integration tests.
Java
// Same as @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Kotlin
// same as @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan
@SpringBootApplication
class MyApplication
fun main(args: Array<String>) {
runApplication<MyApplication>(*args)
}
@SpringBootApplication
also provides aliases to customize the attributes of @EnableAutoConfiguration
and @ComponentScan
.
None of these features are mandatory and you may choose to replace this single annotation by any of the features that it enables.
For instance, you may not want to use component scan or configuration properties scan in your application:
Java
@SpringBootConfiguration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ SomeConfiguration.class, AnotherConfiguration.class })
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Kotlin
@SpringBootConfiguration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import(SomeConfiguration::class, AnotherConfiguration::class)
class MyApplication
fun main(args: Array<String>) {
runApplication<MyApplication>(*args)
}
In this example, MyApplication
is just like any other Spring Boot application except that @Component
-annotated classes and @ConfigurationProperties
-annotated classes are not detected automatically and the user-defined beans are imported explicitly (see @Import
).
7. Running Your Application
One of the biggest advantages of packaging your application as a jar and using an embedded HTTP server is that you can run your application as you would any other.
The sample applies to debugging Spring Boot applications.
You do not need any special IDE plugins or extensions.
This section only covers jar-based packaging.
If you choose to package your application as a war file, see your server and IDE documentation.
7.1. Running From an IDE
You can run a Spring Boot application from your IDE as a Java application.
However, you first need to import your project.
Import steps vary depending on your IDE and build system.
Most IDEs can import Maven projects directly.
For example, Eclipse users can select Import…
→ Existing Maven Projects
from the File
menu.
If you cannot directly import your project into your IDE, you may be able to generate IDE metadata by using a build plugin.
Maven includes plugins for Eclipse and IDEA.
Gradle offers plugins for various IDEs.
If you accidentally run a web application twice, you see a “Port already in use” error.
Spring Tools users can use the Relaunch
button rather than the Run
button to ensure that any existing instance is closed.
7.2. Running as a Packaged Application
If you use the Spring Boot Maven or Gradle plugins to create an executable jar, you can run your application using java -jar
, as shown in the following example:
$ java -jar target/myapplication-0.0.1-SNAPSHOT.jar
It is also possible to run a packaged application with remote debugging support enabled.
Doing so lets you attach a debugger to your packaged application, as shown in the following example:
$ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \
-jar target/myapplication-0.0.1-SNAPSHOT.jar
7.3. Using the Maven Plugin
The Spring Boot Maven plugin includes a run
goal that can be used to quickly compile and run your application.
Applications run in an exploded form, as they do in your IDE.
The following example shows a typical Maven command to run a Spring Boot application:
$ mvn spring-boot:run
You might also want to use the MAVEN_OPTS
operating system environment variable, as shown in the following example:
$ export MAVEN_OPTS=-Xmx1024m
7.4. Using the Gradle Plugin
The Spring Boot Gradle plugin also includes a bootRun
task that can be used to run your application in an exploded form.
The bootRun
task is added whenever you apply the org.springframework.boot
and java
plugins and is shown in the following example:
$ gradle bootRun
You might also want to use the JAVA_OPTS
operating system environment variable, as shown in the following example:
$ export JAVA_OPTS=-Xmx1024m
7.5. Hot Swapping
Since Spring Boot applications are plain Java applications, JVM hot-swapping should work out of the box.
JVM hot swapping is somewhat limited with the bytecode that it can replace.
For a more complete solution, JRebel can be used.
The spring-boot-devtools
module also includes support for quick application restarts.
See the Hot swapping “How-to” for details.
8. Developer Tools
Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant.
The spring-boot-devtools
module can be included in any project to provide additional development-time features.
To include devtools support, add the module dependency to your build, as shown in the following listings for Maven and Gradle:
Maven
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
Gradle
dependencies {
developmentOnly("org.springframework.boot:spring-boot-devtools")
}
Devtools might cause classloading issues, in particular in multi-module projects.
Diagnosing Classloading Issues explains how to diagnose and solve them.
Developer tools are automatically disabled when running a fully packaged application.
If your application is launched from java -jar
or if it is started from a special classloader, then it is considered a “production application”.
You can control this behavior by using the spring.devtools.restart.enabled
system property.
To enable devtools, irrespective of the classloader used to launch your application, set the -Dspring.devtools.restart.enabled=true
system property.
This must not be done in a production environment where running devtools is a security risk.
To disable devtools, exclude the dependency or set the -Dspring.devtools.restart.enabled=false
system property.
Flagging the dependency as optional in Maven or using the developmentOnly
configuration in Gradle (as shown above) prevents devtools from being transitively applied to other modules that use your project.
Repackaged archives do not contain devtools by default.
If you want to use a certain remote devtools feature, you need to include it.
When using the Maven plugin, set the excludeDevtools
property to false
.
When using the Gradle plugin, configure the task’s classpath to include the developmentOnly
configuration.
8.1. Diagnosing Classloading Issues
As described in the Restart vs Reload section, restart functionality is implemented by using two classloaders.
For most applications, this approach works well.
However, it can sometimes cause classloading issues, in particular in multi-module projects.
To diagnose whether the classloading issues are indeed caused by devtools and its two classloaders, try disabling restart.
If this solves your problems, customize the restart classloader to include your entire project.
8.2. Property Defaults
Several of the libraries supported by Spring Boot use caches to improve performance.
For example, template engines cache compiled templates to avoid repeatedly parsing template files.
Also, Spring MVC can add HTTP caching headers to responses when serving static resources.
While caching is very beneficial in production, it can be counter-productive during development, preventing you from seeing the changes you just made in your application.
For this reason, spring-boot-devtools disables the caching options by default.
Cache options are usually configured by settings in your application.properties
file.
For example, Thymeleaf offers the spring.thymeleaf.cache
property.
Rather than needing to set these properties manually, the spring-boot-devtools
module automatically applies sensible development-time configuration.
The following table lists all the properties that are applied:
Name
Default Value
server.error.include-binding-errors
always
server.error.include-message
always
server.error.include-stacktrace
always
server.servlet.jsp.init-parameters.development
true
server.servlet.session.persistent
true
spring.freemarker.cache
false
spring.graphql.graphiql.enabled
true
spring.groovy.template.cache
false
spring.h2.console.enabled
true
spring.mustache.servlet.cache
false
spring.mvc.log-resolved-exception
true
spring.reactor.netty.shutdown-quiet-period
0s
spring.template.provider.cache
false
spring.thymeleaf.cache
false
spring.web.resources.cache.period
0
spring.web.resources.chain.cache
false
If you do not want property defaults to be applied you can set spring.devtools.add-properties
to false
in your application.properties
.
Because you need more information about web requests while developing Spring MVC and Spring WebFlux applications, developer tools suggests you to enable DEBUG
logging for the web
logging group.
This will give you information about the incoming request, which handler is processing it, the response outcome, and other details.
If you wish to log all request details (including potentially sensitive information), you can turn on the spring.mvc.log-request-details
or spring.codec.log-request-details
configuration properties.
8.3. Automatic Restart
Applications that use spring-boot-devtools
automatically restart whenever files on the classpath change.
This can be a useful feature when working in an IDE, as it gives a very fast feedback loop for code changes.
By default, any entry on the classpath that points to a directory is monitored for changes.
Note that certain resources, such as static assets and view templates, do not need to restart the application.
If you are restarting with Maven or Gradle using the build plugin you must leave the forking
set to enabled
.
If you disable forking, the isolated application classloader used by devtools will not be created and restarts will not operate properly.
Automatic restart works very well when used with LiveReload.
See the LiveReload section for details.
If you use JRebel, automatic restarts are disabled in favor of dynamic class reloading.
Other devtools features (such as LiveReload and property overrides) can still be used.
DevTools relies on the application context’s shutdown hook to close it during a restart.
It does not work correctly if you have disabled the shutdown hook (SpringApplication.setRegisterShutdownHook(false)
).
DevTools needs to customize the ResourceLoader
used by the ApplicationContext
.
If your application provides one already, it is going to be wrapped.
Direct override of the getResource
method on the ApplicationContext
is not supported.
Automatic restart is not supported when using AspectJ weaving.
8.3.1. Logging Changes in Condition Evaluation
By default, each time your application restarts, a report showing the condition evaluation delta is logged.
The report shows the changes to your application’s auto-configuration as you make changes such as adding or removing beans and setting configuration properties.
To disable the logging of the report, set the following property:
Properties
spring.devtools.restart.log-condition-evaluation-delta=false
Yaml
spring:
devtools:
restart:
log-condition-evaluation-delta: false
8.3.2. Excluding Resources
Certain resources do not necessarily need to trigger a restart when they are changed.
For example, Thymeleaf templates can be edited in-place.
By default, changing resources in /META-INF/maven
, /META-INF/resources
, /resources
, /static
, /public
, or /templates
does not trigger a restart but does trigger a live reload.
If you want to customize these exclusions, you can use the spring.devtools.restart.exclude
property.
For example, to exclude only /static
and /public
you would set the following property:
Properties
spring.devtools.restart.exclude=static/**,public/**
Yaml
spring:
devtools:
restart:
exclude: "static/**,public/**"
If you want to keep those defaults and add additional exclusions, use the spring.devtools.restart.additional-exclude
property instead.
8.3.3. Watching Additional Paths
You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath.
To do so, use the spring.devtools.restart.additional-paths
property to configure additional paths to watch for changes.
You can use the spring.devtools.restart.exclude
property described earlier to control whether changes beneath the additional paths trigger a full restart or a live reload.
8.3.4. Disabling Restart
If you do not want to use the restart feature, you can disable it by using the spring.devtools.restart.enabled
property.
In most cases, you can set this property in your application.properties
(doing so still initializes the restart classloader, but it does not watch for file changes).
If you need to completely disable restart support (for example, because it does not work with a specific library), you need to set the spring.devtools.restart.enabled
System
property to false
before calling SpringApplication.run(…)
, as shown in the following example:
Java
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(MyApplication.class, args);
}
}
Kotlin
@SpringBootApplication
object MyApplication {
@JvmStatic
fun main(args: Array<String>) {
System.setProperty("spring.devtools.restart.enabled", "false")
SpringApplication.run(MyApplication::class.java, *args)
}
}
8.3.5. 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
spring.devtools.restart.trigger-file=.reloadtrigger
Yaml
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.
8.3.6. 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 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.
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, as shown in the following example:
Properties
restart.exclude.companycommonlibs=/mycorp-common-[\\w\\d-\\.]+\\.jar
restart.include.projectcommon=/mycorp-myproj-[\\w\\d-\\.]+\\.jar
Yaml
restart:
exclude:
companycommonlibs: "/mycorp-common-[\\w\\d-\\.]+\\.jar"
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.
8.3.7. 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.
8.4. 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.
8.5. 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
spring.devtools.restart.trigger-file=.reloadtrigger
Yaml
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.
8.5.1. 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
spring.devtools.restart.poll-interval=2s
spring.devtools.restart.quiet-period=1s
Yaml
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.
8.6. 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.
8.6.1. Running the Remote Client Application
The remote client application is designed to be run from within your IDE.
You need to run org.springframework.boot.devtools.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 org.springframework.boot.devtools.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.0.13)
2023-11-23T09:04:20.386Z INFO 35386 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication v3.0.13 using Java 17.0.9 with PID 35386 (/Users/myuser/.m2/repository/org/springframework/boot/spring-boot-devtools/3.0.13/spring-boot-devtools-3.0.13.jar started by myuser in /opt/apps/)
2023-11-23T09:04:20.393Z INFO 35386 --- [ main] o.s.b.devtools.RemoteSpringApplication : No active profile set, falling back to 1 default profile: "default"
2023-11-23T09:04:20.794Z INFO 35386 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2023-11-23T09:04:20.841Z INFO 35386 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 1.048 seconds (process running for 1.454)
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.
8.6.2. 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.
9. Packaging Your Application for Production
Executable jars can be used for production deployment.
As they are self-contained, they are also ideally suited for cloud-based deployment.
For additional “production ready” features, such as health, auditing, and metric REST or JMX end-points, consider adding spring-boot-actuator
.
See actuator.html for details.
10. What to Read Next
You should now understand how you can use Spring Boot and some best practices that you should follow.
You can now go on to learn about specific Spring Boot features in depth, or you could skip ahead and read about the “production ready” aspects of Spring Boot.