【SpringBoot 2學習筆記】《一》入門初體驗

一、SpringBoot2入門介紹

1.1、SpringBoot特性介紹

Spring Boot整體上簡化開發Spring應用的框架構成,整合了Spring關聯技術棧,提供了J2EE開發的一站式解決方案。其主要特點如下:

  • Spring Boot伴隨着Spring 4.0誕生的,繼承了Spring框架原有的優秀基因。

  • 遵循“約定優先於配置”的原則,使用Spring Boot只需很少的配置,大部分的時候直接使用默認的配置即可。SpringBoot會根據項目依賴來自動配置Spring框架,極大減少了項目所使用的配置。

  • 對主流開發框架無配置集成,自動整合第三方框架。

  • Spring Boot可以JAR包的形式獨立運行。使用java -jar命令或者在項目的主程序中執行main函數就可以成功運行項目。

  • Spring Boot內嵌Servlet 容器,可以選擇內嵌Tomcat、Jetty 等Web容器,無須以war包形式部署項目。

  • 提供starter簡化Maven配置,基本上可以做到自動化配置,高度封裝,開箱即用。

  • Spring Boot提供了準生產環境的應用監控。

  • 支持分佈式開發,與Spring Cloud的微服務無縫結合。

1.2、RESTful風格微服務

RESTful架構風格規定,數據的元操作,即CRUD(增刪查改)操作,分別對應於HTTP方法:GET用來獲取資源,POST用來新建資源(也可以用於更新資源),PUT用來更新資源,DELETE用來刪除資源,這樣就統一了數據操作的接口,僅通過HTTP方法,就可以完成對數據的所有增刪查改工作。

  • GET(SELECT):從服務器取出資源(一項或多項)。

  • POST(CREATE):在服務器新建一個資源。

  • PUT(UPDATE):在服務器更新資源(客戶端提供完整資源數據)。

  • PATCH(UPDATE):在服務器更新資源(客戶端提供需要修改的資源數據)。

  • DELETE(DELETE):從服務器刪除資源。

1.3、環境準備

項目中使用環境及相關要求如下:

  • JDK:Spring Boot 2.0 要求 Java 8 作爲最低版本,現在許多現有的API已更新,以便利用 Java 8 的特性,例如:接口上的默認方法,函數回調以及新的 API。

  • Maven:Maven 3.3以上

  • IDE:SpringToolSuite4( https://spring.io/tools

  • SpringBoot 2.X

1.4、SpringBoot2入門之HelloWorld

因爲Spring官方提供的STS已經整合了開發的相關各種組件,所以下載下來後可以直接使用。如果你使用標準的Eclipse的話,需要進行Maven,STS插件的安裝,可以自行百度解決。接下來使用STS4來進行第一個SpringBoot微服務的開發,採用經典的HelloWorld作爲示例。

1、點擊熟悉的菜單File→New→Spring Starter Project創建項目,如下圖所示。也可以選擇Project在選用具體的我們需要創建的項目。

 

2、使用 https://start.spring.io/ 快速創建一個SpringBoot2項目

 

※ 注意: 因爲是入門的HelloWorld,因此沒有引入太多的內容。在現實的開發中,可能還需要選擇NoSQL 開發工具(例如Redis、MongoDB等),還有數據庫MySQL,以及持久層MyBatis等項目的依賴。

3、默認創建的工程因爲引用Junit版本導致默認生成的代碼有紅色錯誤。我們通過在POM文件中引入對應的 JUnit5來解決該問題。

    <!-- Junit 5 -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <scope>test</scope>
    </dependency>

 

 

4、現在我們創建一個HelloController來演示運行的過程。瀏覽器發送hello請求,服務器接受請求並處理,響應歡迎的字符串。

 

HelloController.java

package com.example.demo.controller;
​
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
​
@RestController
@RequestMapping("/api")
public class HelloController {
​
    @GetMapping("/hello/{userName}")
    public String hello(@PathVariable("userName") String userName) {
        return "Welcome To SpringBoot 2 : " + userName;
    }
}

5、啓動我們的SpringBoot項目並驗證。

使用右鍵選擇啓動類,可以通過途中標記的兩中方式啓動。兩種方式的區別是使用“Run As Spring Boot APP”時,main函數中STS會爲我們添加啓動參數。具體可以自行打斷點查看。

 

啓動後使用瀏覽器訪問我們的第一個應用接口地址。返回結果如下:

 

 

1.5、SpringBoot2 HelloWorld分析

1.5.1 POM文件說明

POM文件主要是描述SpringBoot2.x中Maven的配置內容,所以稱之爲項目對象模型(Project Object Model),其主要內容參考如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  
  <!-- 依賴的SpringBoot父類,包含了大量配置好的依賴管理方便版本統一管理,後面項目添加依賴時,依賴的版本和父類一致的可以不用寫新添加依賴的版本號 --> 
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.0.BUILD-SNAPSHOT</version> <!-- 具體的Spring Boot版本 -->
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  
  <!-- 項目工程信息:Maven GAV座標 -->
  <!-- 組織機構/頂層項目 -->
  <groupId>com.example</groupId>
  <!-- 項目/庫 -->
  <artifactId>HelloWorld</artifactId>
  <!-- 唯一發行版本號 -->
  <version>0.0.1-SNAPSHOT</version>
  <!-- 項目名稱 -->
  <name>HelloWorld</name>
  <!-- 項目描述 -->
  <description>Demo project for Spring Boot</description>
  <!--Maven打包項目的方式:jar或者war -->
  <packaging>jar</packaging>
​
  <!-- 配置項信息,例如JDK版本(必配),編碼類型等其他配置信息 -->
  <properties>
    <java.version>1.8</java.version>
  </properties>
​
  <dependencies>
    <!-- 創建SpringBoot的WEB項目時,WEB啓動器(默認集成tomcat)  -->
    <!-- 注意spring-boot-starter-web 而不是 spring-boot-starter -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
​
    <!--測試啓動器 可以不用考慮-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    
    <!-- SpringBoot2.X 需要引入Junit5 解決默認4.X中註解問題 -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
​
  <!-- 引用插件:直接使用Maven來進行編譯打包 -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
​
  <repositories>
    <!-- 用來配置maven項目的遠程倉庫, 現在使用默認。也可以搭建自己的Maven庫 -->
    <repository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
    </repository>
    <repository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>
  
  <pluginRepositories>
    <!-- 用來配置maven插件的遠程倉庫 -->
    <pluginRepository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
    </pluginRepository>
    <pluginRepository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </pluginRepository>
  </pluginRepositories>
​
</project>

注意:pom.xml 文件修改保存後,Maven自動下載所需的JAR

 

1.5.2 SpringBoot入口類

package com.example.demo;
​
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
​
/**
 *  @SpringBootApplication 標註這是SpringBoot項目的主程序類
 */
@SpringBootApplication
public class HelloWorldApplication {
​
  public static void main(String[] args) {
    
    // SpringApplication: 從main方法啓動Spring應用的類
    SpringApplication.run(HelloWorldApplication.class, args);
  }
​
}

​@SpringBootApplication: Spring Boot應用,該應用標註在某個類上就說明這個類是SpringBoot的主配置類,SpringBoot就運行這個類的main方法來啓動SpringBoot應用。

我們來看一下SpringBootApplication:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
// Spring Boot的配置類
@SpringBootConfiguration
// 開啓自動配置功能。這個註解告訴SpringBoot開啓自動配置功能,只有加上該註解後,自動配置才能生效;
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
@ConfigurationPropertiesScan
public @interface SpringBootApplication {

1.5.3 啓動控制檯

根據控制檯的信息可以瞭解當前工程的Spring Boot的版本、Apache Tomcat 的版本、監聽的端口、Spring WebApplicationContext創建信息等日誌信息。另外,在信息上方看到了一個Spring 的圖形,該圖形還可以自行定製。 ​

​
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.2.0.BUILD-SNAPSHOT)
​
// 啓動應用
2019-11-10 10:48:35.448  INFO 14048 --- [           main] com.example.demo.HelloWorldApplication   : Starting HelloWorldApplication on 20190823-032019 with PID 14048 (C:\StsEclipse4.3.2\workspace\HelloWorld\target\classes started by Administrator in C:\StsEclipse4.3.2\workspace\HelloWorld)
// 查找active profile,沒有設定的情況下則設爲default。
2019-11-10 10:48:35.452  INFO 14048 --- [           main] com.example.demo.HelloWorldApplication   : No active profile set, falling back to default profiles: default
// 進行Tomcat初始化,端口默認設定爲8080,設置訪問方式爲http。
2019-11-10 10:48:36.973  INFO 14048 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
// 啓動Tomcat服務。
2019-11-10 10:48:36.989  INFO 14048 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
// 啓動Servlet引擎。
2019-11-10 10:48:36.989  INFO 14048 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.27]
// 初始化Spring內嵌的WebApplicationContext。
2019-11-10 10:48:37.096  INFO 14048 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
// 完成Spring內嵌的WebApplicationContext的初始化。
2019-11-10 10:48:37.097  INFO 14048 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1560 ms
2019-11-10 10:48:37.278  INFO 14048 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
// Tomcat啓動完成
2019-11-10 10:48:37.450  INFO 14048 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
// 整個應用啓動時間
2019-11-10 10:48:37.453  INFO 14048 --- [           main] com.example.demo.HelloWorldApplication   : Started HelloWorldApplication in 2.415 seconds (JVM running for 3.015)

1.5.4 配置文件

SpringBoot2使用一個全局的配置文件,文件名是固定的,可以在Spring Boot項目的src/main/resources目錄下或者在類路徑的/config目錄下創建一個全局的配置文件application.properties或者是後綴爲.yml的application.yml文件。通過修改配置文件的配置項來修改SpringBoot自動配置的默認值,SpringBoot2在底層都給我們自動配置好。在實際開發中我比較習慣使用application.properties文件作爲應用的全局配置文件。

  • application.properties

  • application.yml

※YML文件格式是YAML (YAML Aint Markup Language)編寫的文件格式,YAML是一種直觀的能夠被電腦識別的的數據數據序列化格式,並且容易被人類閱讀,容易和腳本語言交互的,可以被支持YAML庫的不同的編程語言程序導入。YML文件是以數據爲核心的,比傳統的xml方式更加簡潔。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章