简单的Spring Boot Web开发
上一篇:构建第一个Spring Boot项目
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
值得一提的是:在pom.xml中有这两个模块:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- spring-boot-starter:核心模块,包括自动配置的支持,日志和YAML
- spring-boot-starter-test:测试模块、包括JUnit, Hamcrest, Mockito
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String hello() {
return "hello!Springboot";
}
}
@RestController:WebController里面的方法都以JSON格式输出,不需要配置jackjson,如果将@RestController改为@Controller,就代表输出为页面内容
启动主程序,打开浏览器访问 http://localhost:8080/hello ,页面上就会出现 hello!Springboot
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String index(String name) {
return "hello!" + name;
}
}
重新主程序,打开浏览器访问 http://localhost:8080/hello?name=variable%20name
-
我们经过上面两次小实验发现,一旦修改Controller类里面的内容,就需要重新启动程序才能生效,为了解决这个问题Spring Boot 提供了另外一个组件来解决:热部署
-
什么是热部署?就是在应用正在运行的时候升级软件,却不需要重新启动应用。
-
热启动就需要用到我们一开始引入的另外一个组件:Devtools。它是Spring Boot提供的一组开发工具包,其中就包含我们需要的热部署功能,但是我们需要做一些配置才能使用。
-
在pom.xml > dependencies 中添加optional属性,并设置为true:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-Devtools</artifactId>
<optional>true</optional>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
-
IDEA.2019.1: File – Setting – Build,Execution,Deployment – Compiler:勾选Build project automatically,如果是更低版本,则勾选make project automatically
-
在IDEA界面使用快捷键:Ctrl + Shift + A ,输入Registry 找到选项并勾选compile.automake.allow.when.app.running
以上配置完成之后,IDEA就支持热部署了,我们可以试着去改动一下代码就会发现Spring Boot会自动重新加载,不需要手动重新部署了