1. SpringBoot 介绍


  • SpringBoot 对 Spring 平台和第三方库进行了整合,可创建可以运行的、独立的、生产级的基于 Spring 的应用程序。(大多数 SpringBoot 应用程序只需要很少的 Spring 配置。)
  • SpringBoot 可以使用 java -jar 或更传统的 war 部署启动的 Java 应用程序进行创建,可以内嵌 Tomcat、Jetty、Undertow 容器,快速启动 web 程序。

    1.1. 设计目标

  • 为所有 Spring 开发提供更快且可通用的入门体验。

  • 开箱即用,可以根据需求快速调整默认值。
  • 提供大型项目(例如嵌入式服务器、运行状况检查和统一配置)通用的一系列非功能性功能。
  • 绝对没有代码生成,也不需要 XML 配置。

    1.2. SpringBoot 优势快速预览

    image.png

    2. 开发第一个 SpringBoot 项目


2.1. 依赖(pom.xml)

  • Maven 依赖管理 - spring-boot-dependencies 提供了 SB 支持的依赖,以及相关的版本定义。

    1. <dependencyManagement>
    2. <dependencies>
    3. <dependency>
    4. <groupId>org.springframework.boot</groupId>
    5. <artifactId>spring-boot-dependencies</artifactId>
    6. <version>2.1.3.RELEASE</version>
    7. <type>pom</type>
    8. <scope>import</scope>
    9. </dependency>
    10. </dependencies>
    11. </dependencyManagement>
  • 引入 web 开发相关的依赖(无需再指定版本,由 spring-boot-dependencies 定义)

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter-web</artifactId>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.springframework.boot</groupId>
    8. <artifactId>spring-boot-autoconfigure</artifactId>
    9. </dependency>
    10. </dependencies>

2.2. 添加启动类

  1. @SpringBootApplication
  2. public class SpringbootDemoApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(SpringbootDemoApplication.class, args);
  5. }
  6. }

2.3. 添加 Controller

  1. @RestController
  2. public class MyController {
  3. @GetMapping("index")
  4. public String index() {
  5. return "hello world -maven";
  6. }
  7. }

3. 运行你的 SpringBoot 程序


  • 通过 IDEA 运行 main 方法。
  • maven 插件运行:mvn spring-boot:run,需要添加 spring-boot-maven-plugin 到我们的 pom.xml 文件中。
  • 创建可执行的 jar,需要添加 spring-boot-maven-plugin 到我们的 pom.xml 文件中。
    • 打包命令:mvn package
    • 执行命令:java -jar xxx.jar
    • 注意事项:jar 文件生成在 target 目录下,*.jar.original 这个文件一般很小,这是打包可执行 jar 文件之前的原始 jar。

      4. SpringBoot 中通用的约定


  • 注解默认扫描的包目录 basePackage 为启动类 Main 函数入口所在的包路径;
  • 配置文件约定是 classpath 目录下的 application.yml 或者 application.properties;
  • web 开发的静态文件放在 classpath,访问的顺序依次是:/META-INF/resources -> resources -> static -> public;
  • web 开发中页面模板,约定放在 classpath 目录,/templates/ 目录下。