简介
大家可能都听说过开发Node.js应用时可以使用多种工具对开发者提供便利,如WebPack提供了开发者服务器来支持js应用动态更替,并在保存文件时自动刷新浏览器。Spring Boot也提供了相似的开发者工具,让我们更快速、更舒心的开发Spring Boot应用。大家看完本教程就可以学会如何如用Spring Boot开发者工具进行自动重启和自动刷新页面。
自动重启原理
Spring Boot的开发者工具会为应用创建两个classloader。一个是用来加载不会变动的类,称为base classloader。另一个是restart classloader,用来加载经常变动的类,默认情况下Spring Boot开发者工具会监控classpath下所有的类。当有类变动时,旧的restart classloader就会被丢弃,然后再创建一个新的,以此来加快重启速度。
基础环境
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
项目源码
创建项目
使用IntelliJ创建一个maven项目:
- groupdId: zxuqian.cn
- artifactId: devtools
使用如下pom.xml
文件配置:
复制代码 4.0.0 cn.zxuqian devtools 0.0.1-SNAPSHOT jar devtools Showcase project for Spring Boot developer tools org.springframework.boot spring-boot-starter-parent 2.1.0.BUILD-SNAPSHOT UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin spring-snapshots https://repo.spring.io/snapshot true spring-milestones https://repo.spring.io/milestone spring-snapshots https://repo.spring.io/snapshot spring-milestones https://repo.spring.io/milestone
这里我们用了最新的snapshop版本的spring boot 2.1.0,然后添加spring-boot-devtools
依赖,并把它设置为optional
的,那么这样在最后打包的产品环境中,devtools将不会被打包进来。
接下来添加一个测试用的控制器cn.zxuqian.devtools.controller.HelloController
:
package cn.zxuqian.devtools.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloController { @RequestMapping("/") public String hello() { return "hello world"; }}复制代码
然后创建cn.zxuqian.devtools.DevtoolsApplication
类配置Spring Boot应用:
package cn.zxuqian.devtools;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DevtoolsApplication { public static void main(String[] args) { SpringApplication.run(DevtoolsApplication.class, args); }}复制代码
安装LiveReload插件
从官网下载LiveReload的Chrome或Firefox或Safari浏览器插件,然后启用此插件。
测试
使用spring-boot:run
插件启动此应用,在浏览器打开http://localhost:8080
会看到hello world
字样。然后在我们的控制器中把返回值修改一下,如改为:Hola!
,在IntelliJ中,我们必须要执行Build->Build Project
才能重新编译新改动的代码,我们也可以用快捷键command + (fn) + F9
mac下,来执行编译。稍等几秒就会看到浏览器自动刷新为修改后的值了。
欢迎访问我的博客: