Spring boot devtools что это
Spring boot devtools что это
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, simply add the module dependency to your build:
repackaged archives do not contain devtools by default. If you want to use certain remote devtools feature, you’ll need to disable the excludeDevtools build property to include it. The property is supported with both the Maven and Gradle plugins.
20.1 Property defaults
Several of the libraries supported by Spring Boot use caches to improve performance. For example, template engines will cache compiled templates to avoid repeatedly parsing template files. Also, Spring MVC can add HTTP caching headers to responses when serving static resources.
Whilst 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 will disable those 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 will automatically apply sensible development-time configuration.
For a complete list of the properties that are applied see DevToolsPropertyDefaultsPostProcessor.
20.2 Automatic restart
Applications that use spring-boot-devtools will 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 folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.
Triggering a restart
You can also start your application via the supported build plugins (i.e. Maven and Gradle) as long as forking is enabled since DevTools need an isolated application classloader to operate properly. Gradle and Maven do that by default when they detect DevTools on the classpath.
Automatic restart works very well when used with LiveReload. See below for details. If you use JRebel automatic restarts will be 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 will 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.
The restart technology provided by Spring Boot works by using two classloaders. Classes that don’t change (for example, those from third-party jars) are loaded into a base classloader. Classes that you’re actively developing are loaded into a restart classloader. When the application is restarted, the restart classloader is thrown away and a new one is created. This approach means that application restarts are typically much faster than “cold starts” since the base classloader is already available and populated.
If you find that restarts aren’t quick enough for your applications, or you encounter classloading issues, you could consider reloading technologies such as JRebel from ZeroTurnaround. These work by rewriting classes as they are loaded to make them more amenable to reloading. Spring Loaded provides another option, however it doesn’t support as many frameworks and it isn’t commercially supported.
20.2.1 Excluding resources
if you want to keep those defaults and add additional exclusions, use the spring.devtools.restart.additional-exclude property instead.
20.2.2 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 above to control whether changes beneath the additional paths will trigger a full restart or just a live reload.
20.2.3 Disabling restart
If you don’t want to use the restart feature you can disable it using the spring.devtools.restart.enabled property. In most cases you can set this in your application.properties (this will still initialize the restart classloader but it won’t watch for file changes).
20.2.4 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 this you can use a “trigger file”, which is a special file that must be modified when you want to actually trigger a restart check. Changing the file only triggers the check and the restart will only occur if Devtools has detected it has to do something. The trigger file could be updated manually, or via an IDE plugin.
To use a trigger file use the spring.devtools.restart.trigger-file property.
You might want to set spring.devtools.restart.trigger-file as a global setting so that all your projects behave in the same way.
20.2.5 Customizing the restart classloader
As described in the Restart vs Reload section above, restart functionality is implemented by using two classloaders. For most applications this approach works well, however, sometimes it can cause classloading issues.
The spring-devtools.properties file can contain restart.exclude. and restart.include. prefixed properties. 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 will be applied to the classpath.
All property keys must be unique. As long as a property starts with restart.include. or restart.exclude. it will be considered.
All META-INF/spring-devtools.properties from the classpath will be loaded. You can package files inside your project, or in the libraries that the project consumes.
20.2.6 Known limitations
Unfortunately, several third-party libraries deserialize without considering the context classloader. If you find such a problem, you will need to request a fix with the original authors.
20.3 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 from livereload.com.
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 will have LiveReload support.
20.4 Global settings
20.5 Remote applications
The Spring Boot developer tools are not just limited to local development. You can also use several features when running applications remotely. Remote support is opt-in, to enable it you need to make sure that devtools is included in the repackaged archive:
Then you need to set a spring.devtools.remote.secret property, for example:
Enabling spring-boot-devtools on a remote application is a security risk. You should never enable support on a production deployment.
Remote devtools support is provided in two parts; there is 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.
20.5.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 using the same classpath as the remote project that you’re connecting to. The non-option argument passed to the application should be the remote URL that you are connecting to.
For example, if you are using Eclipse or STS, and you have a project named my-app that you’ve deployed to Cloud Foundry, you would do the following:
A running remote client will look like this:
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’s 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.
20.5.2 Remote update
The remote client will monitor your application classpath for changes in the same way as the local restart. Any updated resource will be pushed to the remote application and (if required) trigger a restart. This can be quite helpful if you are iterating on a feature that uses a cloud service that you don’t have locally. Generally remote updates and restarts are much quicker than a full rebuild and deploy cycle.
Files are only monitored when the remote client is running. If you change a file before starting the remote client, it won’t be pushed to the remote server.
20.5.3 Remote debug tunnel
Java remote debugging is useful when diagnosing issues on a remote application. Unfortunately, it’s not always possible to enable remote debugging when your application is deployed outside of your data center. Remote debugging can also be tricky to setup if you are using a container based technology such as Docker.
To help work around these limitations, devtools supports tunneling of remote debug traffic over HTTP. The remote client provides a local server on port 8000 that you can attach a remote debugger to. Once a connection is established, debug traffic is sent over HTTP to the remote application. You can use the spring.devtools.remote.debug.local-port property if you want to use a different port.
Debugging a remote service over the Internet can be slow and you might need to increase timeouts in your IDE. For example, in Eclipse you can select Java → Debug from Preferences… and change the Debugger timeout (ms) to a more suitable value ( 60000 works well in most situations).
When using the remote debug tunnel with IntelliJ IDEA, all breakpoints must be configured to suspend the thread rather than the VM. By default, breakpoints in IntelliJ IDEA suspend the entire VM rather than only suspending the thread that hit the breakpoint. This has the unwanted side-effect of suspending the thread that manages the remote debug tunnel, causing your debugging session to freeze. When using the remote debug tunnel with IntelliJ IDEA, all breakpoints should be configured to suspend the thread rather than the VM. Please see IDEA-165769 for further details.
Java Blog
Spring Boot инструменты разработчика
Spring Boot включает в себя дополнительный набор инструментов, которые могут сделать процесс разработки приложений более приятным. Модуль spring-boot-devtools может быть включен в любой проект для предоставления дополнительных функций времени разработки. Чтобы включить поддержку devtools, добавьте зависимость модуля в свою сборку, как показано в следующих листингах для Maven и Gradle:
Переупакованные архивы по умолчанию не содержат devtools. Если вы хотите использовать определенную удаленную функцию devtools, вам нужно отключить свойство сборки excludeDevtools, чтобы включить его. Свойство поддерживается как плагинами Maven, так и Gradle.
Свойства по умолчанию
Несколько библиотек, поддерживаемых Spring Boot, используют кэши для повышения производительности. Например, движки шаблонов кэшируют скомпилированные шаблоны, чтобы избежать многократного анализа файлов шаблонов. Кроме того, Spring MVC может добавлять заголовки кэширования HTTP к ответам при обслуживании статических ресурсов.
Хотя кэширование очень полезно в производственной среде, оно может быть непродуктивным во время разработки, мешая вам увидеть изменения, которые вы только что внесли в свое приложение. По этой причине spring-boot-devtools отключает параметры кэширования по умолчанию.
Параметры кэша обычно настраиваются параметрами в вашем файле application.properties. Например, Thymeleaf предлагает свойство spring.thymeleaf.cache. Вместо того, чтобы устанавливать эти свойства вручную, модуль spring-boot-devtools автоматически применяет разумную конфигурацию времени разработки.
Поскольку при разработке приложений Spring MVC и Spring WebFlux требуется больше информации о веб-запросах, инструменты разработчика включат ведение журнала DEBUG для группы веб-журналов. Это даст вам информацию о входящем запросе, какой обработчик его обрабатывает, результат ответа и т. д. Если вы хотите записать все детали запроса (включая потенциально конфиденциальную информацию), вы можете включить spring.http.log-request-details свойство конфигурации.
Если вы не хотите, чтобы свойства по умолчанию применялись, вы можете установить для spring.devtools.add-properties значение false в вашем application.properties.
Полный список свойств, которые применяются devtools, смотрите в DevToolsPropertyDefaultsPostProcessor.
Spring Boot Dev Tools
Introduction to Spring Boot Dev Tools
Spring Boot comes with a lot of features and one of such feature is to help in developer productivity. In this post, we will cover about Spring Boot Dev Tools.
Introduction
One of the main advantages of using Spring Boot is its production ready features, to provide these features, Spring Boot use certain pre-defined configurations.
These features are good but can slow down development with frequent changes in our code and want to see changes immediately. We have the option to use 3rd party tools like Jrebel to help in this but these tools are not free and need a significant amount to get a license (Jrebel is really a great tool and if you can get it, I will highly recommend it). Spring Boot 1.3 introduced Spring Boot Dev Tools module, aimed to help developers in improving the productivity. We will cover following features of the Spring Boot Dev Tool
What is Spring Boot Dev Tools?
They introduced spring Boot Dev Tools module in 1.3 to provide a powerful tool for the development. It helps developers to shorten the development cycle and enable easy deployment and testing during the development. To add use the feature, we need to add a spring-boot-devtools dependency in our build. We need to add the following dependency to our Maven POM
if you are using Gradle as your build tool
Once we perform build, it will add a spring-boot-devtools to our project with its developer-friendly features. Let’s explore these features.
2. Property Defaults
Spring Boot comes with many productions-ready features (Also known as auto-configuration) which include caching for its modules for performance. To boost performance, template engines might cache all compiled templates to avoid template parsing on each request. This is helpful once we deploy our application on production but can be problematic during the development (We might not see changes immediately).
3. Automatic Restart
Typically, as a development life-cycle, we change our code, deploy it and test it and if things are not working as expected we will repeat this cycle. We can always use third-party tools like Jrebel to help in this. Spring Boot Dev Tools provide a similar feature (not as quick as Jrebel) to auto restart. Whenever a file changes in the classpath, spring-boot-devtools module will restart application automatically.
When you start your application with dev tools, you will find similar logs on the startup.
change your application code and perform build, it will trigger an automatic restart. Here are the logs from the restart
Spring Boot use 2 class loader internally to handle this restart. we will cover this feature in another post.
3.1 Exclusion
3.2 Disable Restart
If you want to use the spring-boot-devtools module but like to disable restart feature, you can easily customize it by setting spring.devtools.restart.enabled in your application.properties file, you can disable this feature by setting this on the System property.
4. Live Reload
The dev tools come with an embedded LiveReload server which will automatically trigger browser refresh when resource change. Visit livereload.com for more information.
5. Remote Debugging via HTTP
Spring Boot dev tools provide ready to use remote debugging capabilities, to use this feature on the remote application, we have to make sure that devtools in included in the deployment packet. We can achieve this by setting the excludeDevtools property in our POM.xml file
To allow client to allow remote debugging, we need to make sure following steps
[pullquote align=”normal”]For debugging an application using IntelliJ. Please read Remote debug spring boot application with the maven and IntelliJ [/pullquote]
6. Remote Update
Spring Boot development tool also support update and restart for remote application. The remote client will monitor changes in the local classpath and will trigger a restart after pushing these changes to the remote server. This can be a handy feature if your work involves a cloud service.
6. Global Setting
Summary
Spring Boot Dev Tools comes with many built-in features to help in the development life cycle and make development experience better. We learned how to enable by using these features provided under spring-boot-devtools modules.
Developing with Spring Boot
This section goes into more detail about how you should use Spring Boot. It covers topics such as build systems, auto-configuration, and how to run your applications. We also cover some Spring Boot best practices. Although there is nothing particularly special about Spring Boot (it is just another library that you can consume), there are a few recommendations that, when followed, make your development process a little easier.
If you are starting out with Spring Boot, you should probably read the Getting Started guide before diving into this section.
1. Build Systems
It is strongly recommended that you choose a build system that supports dependency management and that can consume artifacts published to the “Maven Central” repository. We would recommend that you choose Maven or Gradle. It is possible to get Spring Boot to work with other build systems (Ant, for example), but they are not particularly well supported.
1.1. Dependency Management
Each release of Spring Boot provides a curated list of dependencies that it supports. In practice, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you. When you upgrade Spring Boot itself, these dependencies are upgraded as well in a consistent way.
You can still specify a version and override Spring Boot’s recommendations if you need to do so. |
The curated list contains all the Spring modules that you can use with Spring Boot as well as a refined list of third party libraries. The list is available as a standard Bills of Materials ( spring-boot-dependencies ) that can be used with both Maven and Gradle.
Each release of Spring Boot is associated with a base version of the Spring Framework. We highly recommend that you not specify its version. |
1.2. Maven
To learn about using Spring Boot with Maven, see the documentation for Spring Boot’s Maven plugin:
1.3. Gradle
To learn about using Spring Boot with Gradle, see the documentation for Spring Boot’s Gradle plugin:
1.4. Ant
It is possible to build a Spring Boot project using Apache Ant+Ivy. The spring-boot-antlib “AntLib” module is also available to help Ant create executable jars.
To declare dependencies, a typical ivy.xml file looks something like the following example:
A typical build.xml looks like the following example:
1.5. Starters
Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project.
The starters contain a lot of the dependencies that you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies.
The following application starters are provided by Spring Boot under the org.springframework.boot group:
Core starter, including auto-configuration support, logging and YAML
Starter for JMS messaging using Apache ActiveMQ
Starter for using Spring AMQP and Rabbit MQ
Starter for aspect-oriented programming with Spring AOP and AspectJ
Starter for JMS messaging using Apache Artemis
Starter for using Spring Batch
Starter for using Spring Framework’s caching support
Starter for using Cassandra distributed database and Spring Data Cassandra
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive
Starter for using Couchbase document-oriented database and Spring Data Couchbase
Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch
Starter for using Spring Data JDBC
Starter for using Spring Data JPA with Hibernate
Starter for using Spring Data LDAP
Starter for using MongoDB document-oriented database and Spring Data MongoDB
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive
Starter for using Neo4j graph database and Spring Data Neo4j
Starter for using Spring Data R2DBC
Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client
Starter for exposing Spring Data repositories over REST using Spring Data REST
Starter for building MVC web applications using FreeMarker views
Starter for building MVC web applications using Groovy Templates views
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS
Starter for using Spring Integration
Starter for using JDBC with the HikariCP connection pool
Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web
Starter for using jOOQ to access SQL databases with JDBC. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc
Starter for reading and writing json
Starter for JTA transactions using Atomikos
Starter for using Java Mail and Spring Framework’s email sending support
Starter for building web applications using Mustache views
Starter for using Spring Security’s OAuth2/OpenID Connect client features
Starter for using Spring Security’s OAuth2 resource server features
Starter for using the Quartz scheduler
Starter for building RSocket clients and servers
Starter for using Spring Security
Starter for testing Spring Boot applications with libraries including JUnit Jupiter, Hamcrest and Mockito
Starter for building MVC web applications using Thymeleaf views
Starter for using Java Bean Validation with Hibernate Validator
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container
Starter for using Spring Web Services
Starter for building WebFlux applications using Spring Framework’s Reactive Web support
Starter for building WebSocket applications using Spring Framework’s WebSocket support
In addition to the application starters, the following starters can be used to add production ready features:
Starter for using Spring Boot’s Actuator which provides production ready features to help you monitor and manage your application
Finally, Spring Boot also includes the following starters that can be used if you want to exclude or swap specific technical facets:
Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat
Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging
Starter for logging using Logback. Default logging starter
Starter for using Reactor Netty as the embedded reactive HTTP server.
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web
Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat
To learn how to swap technical facets, please see the how-to documentation for swapping web server and logging system.
For a list of additional community contributed starters, see the README file in the spring-boot-starters module on GitHub. |
2. Structuring Your Code
Spring Boot does not require any specific code layout to work. However, there are some best practices that help.
2.1. Using the “default” Package
We recommend that you follow Java’s recommended package naming conventions and use a reversed domain name (for example, com.example.project ). |
2.2. Locating the Main Application Class
We generally recommend that you locate your main application class in a root package above other classes. The @SpringBootApplication annotation is often placed on your main class, and it implicitly defines a base “search package” for certain items. For example, if you are writing a JPA application, the package of the @SpringBootApplication annotated class is used to search for @Entity items. Using a root package also allows component scan to apply only on your project.
The following listing shows a typical layout:
3. Configuration Classes
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.
3.2. Importing XML Configuration
If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration class. You can then use an @ImportResource annotation to load XML configuration files.
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.
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:
You can define exclusions both at the annotation level and by using the property. |
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.
The following example shows a @Service Bean that uses constructor injection to obtain a required RiskAssessor bean:
If a bean has more than one constructor, you will need to mark the one you want Spring to use with @Autowired :
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:
@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.
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:
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
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:
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:
You might also want to use the MAVEN_OPTS operating system environment variable, as shown in the following example:
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:
You might also want to use the JAVA_OPTS operating system environment variable, as shown in the following example:
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:
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. |
8.1. 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.
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.
For a complete list of the properties that are applied by the devtools, see DevToolsPropertyDefaultsPostProcessor. |
8.2. 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.
As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath. The way in which you cause the classpath to be updated depends on the IDE that you are using:
In Eclipse, saving a modified file causes the classpath to be updated and triggers a restart.
In IntelliJ IDEA, building the project ( Build +→+ Build Project ) has the same effect.
If using a build plugin, running mvn compile for Maven or gradle build for Gradle will trigger a restart.
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) ). |
The restart technology provided by Spring Boot works by using two classloaders. Classes that do not change (for example, those from third-party jars) are loaded into a base classloader. Classes that you are actively developing are loaded into a restart classloader. When the application is restarted, the restart classloader is thrown away and a new one is created. This approach means that application restarts are typically much faster than “cold starts”, since the base classloader is already available and populated.
If you find that restarts are not quick enough for your applications or you encounter classloading issues, you could consider reloading technologies such as JRebel from ZeroTurnaround. These work by rewriting classes as they are loaded to make them more amenable to reloading.
8.2.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:
8.2.2. Excluding Resources
If you want to keep those defaults and add additional exclusions, use the spring.devtools.restart.additional-exclude property instead. |
8.2.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.2.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).
8.2.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:
Then your trigger-file property would be:
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. |
8.2.6. Customizing the Restart Classloader
As described earlier 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.
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.2.7. Known Limitations
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.3. 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 from livereload.com.
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. |
8.4. Global Settings
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:
Profiles are not supported in devtools properties/yaml files.
.properties ) and spring.config.activate.on-profile documents in both YAML and Properties files are not supported.
8.4.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:
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.5. 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:
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.
8.5.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:
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.5.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.
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.