Spring Boot学习笔记(二)简单的Spring Boot Web开发

简单的Spring Boot Web开发

上一篇:构建第一个Spring Boot项目
  • 可以在Spring Intializer创建项目时添加,也可以手动在pom.xml文件中添加:

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>
  1. spring-boot-starter:核心模块,包括自动配置的支持,日志和YAML
  2. spring-boot-starter-test:测试模块、包括JUnit, Hamcrest, Mockito
  • 在src–main–java–web下面编写WebController类:
@RestController
public class HelloWorldController {
    @RequestMapping("/hello")
     	public String hello() {
      	 return "hello!Springboot";
  }
}

@RestController:WebController里面的方法都以JSON格式输出,不需要配置jackjson,如果将@RestController改为@Controller,就代表输出为页面内容

启动主程序,打开浏览器访问 http://localhost:8080/hello ,页面上就会出现 hello!Springboot
在这里插入图片描述

  • 实现传参的WebController类:
@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>
  • 在pom.xml > plugins中配置另外一个属性fork,并设置为true:
    <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会自动重新加载,不需要手动重新部署了

  • IDEA默认不是自动编译的,需要我们手动配置后才会自动编译,而热部署依赖于项目的自动编译功能,该模块在完整的打包环境下运行的时候会被禁用。如果使用 java -jar 启动应用或者用一个特定的 classloader 启动,它会认为这是一个“生产环境”。

下一章:Spring Boot单元测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值