【Spring Boot】我的第一个Spring Boot练习

背景

Spring 在 Java 生态的企业级开发项目中极其常用,通常我们为项目引入一项新技术时,不得不考虑如何将新技术与 Spring 整合在一起。

我们知道,预研一项新技术,我们基于 MVP(最简化可实行产品)原则,有助于使我们聚焦在新技术本身,也可以避免其他问题的干扰。

所以,我们经常需要搭建一个最简单的 Spring Boot 的练习,本文做个简单的记录。

要提前准备什么?

  1. 基础的 Java 知识
  2. 好用的 IDE(集成开发环境),本文使用 IDEA
  3. JDK(Java 开发工具),本文使用 JDK8

搭建步骤

spring initializr 的网站生成 Spring Boot 的脚手架,本文加入了 “Web 模块”,使用的具体配置如下:

点击 GENERATE 就能生成脚手架的代码并下载下来,然后我们解压代码,并把代码引入IDEA。

为了提供Web服务用于测试,我们添加一个Controller,下文的Controller的意图是添加一个“心跳接口”,如果“心跳接口”返回“SUCCESS”,表示应用的接口服务正常:

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HeartBeatController {

    @GetMapping("/heartBeat")
    public String hello() {
        return "SUCCESS";
    }

}

然后,我们运行 com.example.demo.DemoApplication#main 方法即可启动项目:

启动,及阅读启动日志

如无意外,启动后会看到如下日志(日志为了方便查看,做了部分内容删减):

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.5)

com.example.demo.DemoApplication         : Starting DemoApplication using Java 1.8.0_191 on USER-20200704PZ with PID 816 (D:\workspace\demo\target\classes started by Administrator in D:\workspace\demo)
com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
o.apache.catalina.core.StandardService   : Starting service [Tomcat]
org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.53]
o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1861 ms
o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
com.example.demo.DemoApplication         : Started DemoApplication in 3.272 seconds (JVM running for 4.028)
o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms

通过阅读启动日志,我们可以知道最简单的 Spring Boot 相应的启动过程:

  1. 打印 Banner 文字图案,当然,这个文字图案是可配置的,请自行查询
  2. 打印什么用户什么机器哪个进程号使用什么版本的JDK启动服务
  3. 打印使用的 Profile,本文是default
  4. 打印启动服务器所使用的服务端口,本文是8080
  5. 启动服务
  6. 启动 Servlet 引擎,本文是 Apache Tomcat/9.0.53
  7. 初始化WebApplicationContext
  8. Web服务器启动完成,打印使用的协议端口上下文路径,本文分别是:http8080、空上下文路径
  9. 打印启动应用所耗费的时间JVM运行的时间
  10. 打印初始化Spring DispatcherServlet 的过程

最后,我们使用浏览器访问 http://127.0.0.1:8080/heartBeat 即可看到效果:

posted @ 2021-10-12 23:26  nick_huang  阅读(394)  评论(0编辑  收藏  举报