SpringBoot Lecture 9: SpringBoot configuration hot deployment devtools tool

SpringBoot Lecture 9: SpringBoot configuration hot deployment devtools tool

This article is the ninth lecture of SpringBoot. In the development and debugging of SpringBoot, if I need to restart and debug every line of code modification, it may be time-consuming; the SpringBoot team provides the spring-boot-devtools (devtools for short) plug-in for this problem, which tries to improve the efficiency of development and debugging .

1. Prepare knowledge points

1.1. What are hot deployment and hot loading?

Hot deployment and hot loading are the ability to automatically update (reload or replace classes, etc.) applications while the application is running. (The solution provided by spring-boot-devtools also needs to be restarted, but it can be automatically loaded without manual restart .)

Strictly speaking, we need to distinguish between hot deployment and hot loading . For Java projects:

  • hot deployment
    • Redeploy the project while the server is running
    • It directly reloads the entire application, which frees memory and is cleaner and more thorough than hot loading, but it is also more time-consuming.
  • hot load
    • Upgrades the application by reloading classes at runtime .
    • The implementation principle of hot loading mainly depends on JVM Lecture 2: Class loading mechanism . The implementation method can be summarized as starting a background thread when the container is started, and regularly detecting changes in the timestamp of the class file. If the timestamp of the class changes, the class will be reloaded .
    • Compared with the reflection mechanism, reflection is to obtain class information at runtime and change program behavior through dynamic calls; hot loading is to change class information by reloading at runtime and directly change program behavior.

1.2. What is LiveLoad?

LiveLoad is a tool that provides automatic loading and updating of browser clients. It is divided into two parts: LiveLoad server and Liveload browser plug-in; devtools has integrated LiveLoad server, so if we develop a web application and expect the browser to refresh automatically, we can consider LiveLoad at this time.

  • img

Only one LiveReload server can run at a time. Before starting the application, make sure no other LiveReload servers are running. If multiple applications are launched from the IDE, only the first application will support LiveReload.

2. Configure devtools to implement hot deployment

We use the following configuration to realize hot deployment in automatic restart mode.

2.1, POM configuration

Add spring-boot-devtools dependency

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <!-- 可以防止将devtools依赖传递到其他模块中 好比 Java 中的 final 类,不能被其他类继承一样 -->
        <optional>true</optional> 
    </dependency>
</dependencies>

2.2, IDEA placement

If you use IDEA development tools, there are usually two ways:

  • Method 1: When there is no configuration, manually trigger the restart update (Command+F9)
    insert image description here
    (you can also use mvn compilecompilation to trigger the restart update)

  • Method 2: IDEA needs to enable runtime compilation and automatically restart the update

Set 1 :

File->Setting->Build,Execution,Deployment->Compile

Check: Build project automatically

  • insert image description here

Setting 2 :
IDEA can be set in the first setting in File->setting->Advanced Settings:

  • insert image description here

2.3, application.yml configuration

spring:
  devtools:
    restart:
      enabled: true  #设置开启热部署
      additional-paths: src/main/java #重启目录
      exclude: WEB-INF/**
  thymeleaf:
    cache: false #使用Thymeleaf模板引擎,关闭缓存

2.4. Use LiveLoad

The spring-boot-devtools module contains an embedded LiveReload server that can be used to trigger a browser refresh when resources change. The LiveReload browser extension supports Chrome, Firefox, and Safari, and you can download it for free from livereload.com.

  • img

Or download from the browser add-on center, such as firefox:

  • img

After installation, you can manage through the following icons

  • img

If you do not want to start the LiveReload server while the application is running, you can set the spring.devtools.livereload.enabled property to false.

Only one LiveReload server can run at a time. Before starting the application, make sure no other LiveReload servers are running. If multiple applications are launched from the IDE, only the first application will support LiveReload.

3. Further understanding

Although some developers will use devtool tools, few can understand deeply; let us understand the following questions to help you further understand.

3.1. The principle of devtool? Why does it restart automatically?

Why is it also restarting the application, why not restart it manually, but suggest using spring-boot-devtools for hot deployment restart ?

spring-boot-devtools uses two class loaders ClassLoader, one ClassLoader loads classes that will not change (third-party jar packages), and the other ClassLoader (restart ClassLoader) loads classes that will change (custom classes).

A file monitoring thread (File Watcher) is started in the background . When a file in the monitored directory changes, the original restart ClassLoader is discarded and a new restart ClassLoader will be reloaded .

Because after the file changes, the third-party jar package will no longer be reloaded, only the custom classes will be loaded, and the loaded classes will be less, so the restart will be faster.

This is why, the same is to restart the application, why not restart it manually, it is recommended to use spring-boot-devtools for hot deployment restart.

There are a few points to note in automatic restart:

  • Automatic restart will record the log

(Record the log under what circumstances to restart)

can be turned off by

spring:
  devtools:
    restart:
      log-condition-evaluation-delta: false
  • Exclude some resources that do not need to be automatically restarted

Some resources don't necessarily need to trigger a restart when they change. 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, /public you would set the following property:

spring:
  devtools:
    restart:
      exclude: "static/**,public/**"

If you want to keep these defaults and add additional exclusions, use this spring.devtools.restart.additional-excludeproperty instead.

  • Custom restart classloader

The restart functionality is implemented by using two classloaders. For most applications, this approach works well. However, it can sometimes cause classloading issues .

By default, any open project in the IDE is loaded using the "restart" classloader, and any regular .jar files are loaded using the "base" classloader. If you're working on a multi-module project, and not every module is imported into your IDE, you may need to customize something. For this, you can create a META-INF/spring-devtools.propertiesfile.

The spring-devtools.properties file can contain properties prefixed with restart.exclude and restart.include . The include element is the item that should be pulled up to the "restart" classloader, and the exclude element is the item that should be pushed down into the "Base" classloader. The value of this property is a regular expression pattern applied to the classpath, as shown in the following example:

restart:
  exclude:
    companycommonlibs: "/mycorp-common-[\\w\\d-\\.]+\\.jar"
  include:
    projectcommon: "/mycorp-myproj-[\\w\\d-\\.]+\\.jar"

More information about it can be found here .

3.2. Will devtool be packaged into Jar?

In principle, devtool should only be used during development and debugging, but it is not needed when running the jar package in the production environment, so will Spring package it into JAR?

  • By default, will not be packaged into the JAR

Developer tools are automatically disabled when running a packaged application . If you start it through java -jar or other special class loaders, it will be considered a "production environment application".

  • If we expect to remotely debug the application

( Do not use in production, only enable it when running on a trusted network or secured with SSL )

In this case, devtool is also capable of remote debugging : the remote client application is designed to be run from within your IDE. You need to org.springframework.boot.devtools.RemoteSpringApplicationrun with the same classpath as the remote project you are connecting to. The only required parameter for the application is the remote URL it connects to.

For example, if using Eclipse or Spring Tools, and you have a project named my-app deployed to Cloud Foundry, do the following:

  1. Select Run Configurations... from the Run menu.
  2. Create a new Java Application "Launch Configuration".
  3. Browse the my-app project.
  4. Use org.springframework.boot.devtools.RemoteSpringApplicationas main class.
  5. Add https://myapp.cfapps.io to Program arguments (or whatever your remote URL is).

A running remote client might look like the following list:

  .   ____          _                                              __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _          ___               _      \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` |        | _ \___ _ __  ___| |_ ___ \ \ \ \
 \\/  ___)| |_)| | | | | || (_| []::::::[]   / -_) '  \/ _ \  _/ -_) ) ) ) )
  '  |____| .__|_| |_|_| |_\__, |        |_|_\___|_|_|_\___/\__\___|/ / / /
 =========|_|==============|___/===================================/_/_/_/
 :: Spring Boot Remote :: 2.5.4

2015-06-10 18:25:06.632  INFO 14938 --- [           main] o.s.b.devtools.RemoteSpringApplication   : Starting RemoteSpringApplication on pwmbp with PID 14938 (/Users/pwebb/projects/spring-boot/code/spring-boot-project/spring-boot-devtools/target/classes started by pwebb in /Users/pwebb/projects/spring-boot/code)
2015-06-10 18:25:06.671  INFO 14938 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a17b7b6: startup date [Wed Jun 10 18:25:06 PDT 2015]; root of context hierarchy
2015-06-10 18:25:07.043  WARN 14938 --- [           main] o.s.b.d.r.c.RemoteClientConfiguration    : The connection to http://localhost:8080 is insecure. You should use a URL starting with 'https://'.
2015-06-10 18:25:07.074  INFO 14938 --- [           main] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2015-06-10 18:25:07.130  INFO 14938 --- [           main] o.s.b.devtools.RemoteSpringApplication   : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105)

3.3. Why does devtool disable the caching option by default?

Some libraries supported by Spring Boot use caching to improve performance . For example, template engines cache compiled templates to avoid parsing template files repeatedly. Additionally, Spring MVC can add HTTP caching headers to responses when serving static resources.

While caching is very beneficial in production, it can be counterproductive during development , preventing you from seeing changes you just made in your application. For this reason, spring-boot-devtools disables the caching option by default.

For example, Thymeleaf provides spring.thymeleaf.cache to set the cache of the template engine. When using the spring-boot-devtools module, there is no need to manually set these properties, because spring-boot-devtools will automatically set them.

So what configurations are automatically set? You can DevToolsPropertyDefaultsPostProcessorfind the corresponding default configuration in the class.

public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostProcessor {
    
    
	static {
    
    
		Map<String, Object> properties = new HashMap<>();
		properties.put("spring.thymeleaf.cache", "false");
		properties.put("spring.freemarker.cache", "false");
		properties.put("spring.groovy.template.cache", "false");
		properties.put("spring.mustache.cache", "false");
		properties.put("server.servlet.session.persistent", "true");
		properties.put("spring.h2.console.enabled", "true");
		properties.put("spring.web.resources.cache.period", "0");
		properties.put("spring.web.resources.chain.cache", "false");
		properties.put("spring.template.provider.cache", "false");
		properties.put("spring.mvc.log-resolved-exception", "true");
		properties.put("server.error.include-binding-errors", "ALWAYS");
		properties.put("server.error.include-message", "ALWAYS");
		properties.put("server.error.include-stacktrace", "ALWAYS");
		properties.put("server.servlet.jsp.init-parameters.development", "true");
		properties.put("spring.reactor.debug", "true");
		PROPERTIES = Collections.unmodifiableMap(properties);
	}

Of course, if you don’t want the applied properties to be set by spring-boot-devtools by default, you can pass spring.devtools.add-properties to false in your application.yml.

3.4. Can devtool do global configuration for all Springboot applications?

Global devtools settings can be configured by adding a spring-boot-devtools.yml file to the $HOME/.config/spring-boot directory .

Any properties added to these files apply to all Spring Boot applications on your machine using devtools. For example, to configure restart to always use a trigger file, you would add the following property to your spring-boot-devtools file:

spring:
  devtools:
    restart:
      trigger-file: ".reloadtrigger"

3.5. If I don't use devtool, what other options are there?

If I don't use devtools, what are my options?

In the actual development process, I will not use the devtool tool , because:

  • devtool itself is based on the restart method, which is still not a real hot replacement solution, JRebel is (it is charged)

  • The most important thing in development and debugging is a trade-off

    • If the overhead of automatic restart is not much different from manual restart, then it is better to manually restart (restart on demand)
    • In most cases, if it is an internal modification of a method or a modification of a static resource , hot update can be performed through Rebuild (Ctrl + Shift + F9) in IDEA
  • insert image description here

  • In addition, there is a tool spring loaded, which can realize hot deployment of modified class files. For details, see the description on its github address .

4. Reference articles

Developing with Spring Boot

Simple use of devtools developer tools

Guess you like

Origin blog.csdn.net/qq_28959087/article/details/131818842