Spring Boot從零入門3_建立Hello World及項目剖析

本文屬於原創,轉載註明出處,歡迎關注微信小程序小白AI博客 微信公衆號小白AI或者網站 https://xiaobaiai.nethtml

[TOC]java

1 前言

上一篇咱們講述了Spring boot的幾個核心模塊,知道了Spring boot是如何減小組件依賴和簡化繁雜的配置的,以及講述了Spring boot減小組件依賴和簡化繁雜配置的內部原理,最後完成了Spring boot的開發環境搭建。這一篇咱們將講述如何建立Spring boot Hello World級別的項目,建立一個簡單的WEB應用,而後咱們對這個項目層層剖析,讓咱們更深的瞭解Spring boot是如何工做的。git

2 名詞術語

名詞術語 釋義
CLI 命令行界面,command-line interface
Marven Apache Maven是一個軟件項目管理和綜合工具,構建自動化系統(如Make,CMake)。基於項目對象模型(POM)的概念,Maven能夠從一箇中心資料片管理項目構建,報告和文件。Maven簡化和標準化項目建設過程,處理編譯,分配,文檔,團隊協做和其餘任務的無縫鏈接。 Maven增長可重用性並負責創建相關的任務;Marven擁有依賴管理功能,它經過簡單的配置就能夠自動從網絡上下載項目所需的依賴
POM 項目對象模型(Project Object Model),它是Maven項目中的文件,使用XML表示,名稱叫作pom.xml;該文件用於管理:源代碼、配置文件、開發者的信息和角色、問題追蹤系統、組織信息、項目受權、項目的url、項目的依賴關係等;Maven世界中,project能夠什麼都沒有,甚至沒有代碼,可是必須包含pom.xml文件
Gradle Gradle是一個徹底開源的構建自動化系統,使用特定編程語言Groovy來書寫配置文件,不一樣於Marven使用XML。如Android開發IDE Android Studio默認就是使用Gradle來構建項目;Gradle與Maven相比更爲靈活,簡單。
JDK8 JDK8或者JDK1.8是因爲自從JDK1.5/JDK5命名方式改變後遺留的新舊命令方式問題。因此JDK8或者JDK1.8也是同一個東西。
STS Spring Tool Suite,Spring Tools 4是適用於你喜歡的編碼環境的下一代Spring工具。不管是你喜歡Eclipse,Visual Studio Code仍是Theia IDE,STS是從頭開始大量重構的,爲開發基於Spring的企業應用程序提供了世界一流的支持。
Thymeleaf Thymeleaf是現代化服務器端的Java模板引擎,不一樣與JSP和FreeMarker,Thymeleaf的語法更加接近HTML,而且也有不錯的擴展性。
註解 註解只有成員變量,沒有方法。註解的成員變量在註解的定義中以「無形參的函數」形式來聲明,如int id();引用時如@TestAnnotation(id=3) 。註解中屬性能夠有默認值,默認值須要用 default 關鍵值指定,如public int id() default -1;註解的提取須要藉助於 Java 的反射技術,反射比較慢,因此註解使用時也須要謹慎計較時間成本。註解主要給編譯器及工具類型的軟件用的。
元註解 元註解是能夠註解到註解上的註解,或者說元註解是一種基本註解,可是它可以應用到其它的註解上面。若是把註解理解爲標籤,元註解也是一張標籤,可是它是一張特殊的標籤,它的做用和目的就是給其餘普通的標籤進行解釋說明的。元標籤有 @Retention、@Documented、@Target、@Inherited、@Repeatable 5 種

3 建立Hello World項目

建立一個Spring boot應用,有下面幾種方式能夠選擇:github

  • 使用IDE工具,如咱們使用的STS4
  • 使用Spring boot CLI工具
  • 使用Spring Initializr網站來建立

下面對這三種方式一一講述如何建立一個Spring boot WEB項目。web

💡 STS(Spring Tool Suite)能夠開發其餘不少類型的項目,這裏僅以Spring boot項目做爲建立示例。spring

3.1 基於STS4建立項目

3.1.1 項目建立

基於STS4建立Spring Web項目,這裏選擇Marven Project項目類型或者是Spring Starter Project項目類型。Spring Stater Project跟下一小節所講的Spring Initializr Website建立項目基本一致,只不過一個是集成在STS中,一個是獨立的Web網站,下一小節細講,這裏就不展開了。這裏選擇Marven Project類型,開始建立。apache

建立Marven項目中,咱們選擇Create a Simple Project,能夠選擇默認工做目錄或者其餘存放項目的目錄,Next後須要咱們填寫一些項目信息,包括:編程

  • groupId:在全部項目中惟一標識你的項目。組ID應該遵循Java的程序包名稱規則。這意味以反向域名開頭(固然這不是強迫的,只是歷史遺留下來的),如:
    • org.apache.maven
    • org.apache.commons
    • org.apache.maven.plugins
    • org.apache.maven.reporting
  • artifactId:是沒有版本的jar的名稱。若是建立了它,那麼能夠選擇任何名稱,包括小寫字母和不是很奇怪的符號。若是是第三方jar,則必須使用該jar的名稱。
  • version:若是發佈了版本,則能夠選擇帶有數字和點(1.0、1.一、1.0.1,...)的任何典型版本。不要使用日期,由於它們一般與SNAPSHOT(快照)構建相關聯。
    若是它是第三方artifact,則不管使用什麼版本,都必須使用其版本號。

點擊完成後,就建立了一個最簡單的Marven項目,僅僅只有一個pom.xml文件,裏面也只有咱們建立的項目信息,接下來咱們須要實現WEB服務器,訪問一個簡單的頁面,頁面顯示出Hello World!小程序

3.1.2 添加工程代碼

添加Spring WEB依賴項到pom.xml中:微信小程序

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xiaobaiai.examples</groupId>
    <artifactId>test_01_helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <!-- 下面爲添加的依賴內容,spring-boot-starter-web -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>複製代碼

第二步,在src/main/java目錄下新建一個Java文件:

填寫PackageName,點擊Finish,建立完成,而後編寫該Java文件:

package com.xiaobaiai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
@Controller
public class Test01HelloworldApplication {
    @RequestMapping("/")
    @ResponseBody
    public String index() {
        return "Hello World!";
    }

    public static void main(String[] args) {
        SpringApplication.run(Test01HelloworldApplication.class, args);
    }
}複製代碼

💡 在STS中,包一鍵導入快捷鍵Ctrl + Shift + o

3.1.3 運行Hell World Web應用

上述修改兩個文件就完成一個基本的Hello World!級別應用,而後就能夠運行了: 選中項目-->菜單欄Run-->Run (Spring boot App)或者直接到工具欄找到快捷按鈕(綠色右箭頭),點擊。接下來就能夠看到在STS中的console(控制檯)中看到Web 服務啓動的過程了,沒有出現錯誤,Tomcat initialized with port(s): 8080 (http),打開瀏覽器,輸入http://localhost:8080回車可看到輸出Hello World!,Demo成功:

3.2 使用Spring Initializr Website建立項目並導入

3.2.1 STS中的Spring Initializr

經過Spring Initializr咱們能夠經過點擊頁面,選擇咱們所須要的依賴項,最終生成項目配置文件和應用文件。通常IDE中也集成了Spring Initializr,如STS中新建一個Spring Starter Project就能夠操做Spring Initializr,在下一小節中咱們將經過網站中的Spring Initializr來實現建立一個Web項目:

3.2.2 網站的中Spring Initializr

在瀏覽器中打開start.spring.io,輸入項目相關信息,並選擇Spring Boot及構建工具等,在DependenciesWeb欄中選中Spring Web,最後點擊綠色按鈕Generate - Ctrl按鈕生成工程文件壓縮包,放於你的工做目錄中並解壓,而後用STS導入該項目:

導入成功後,能夠看到自動生成了上一小節中咱們建立的pom.xmlXXApplication.java文件以及測試文件XXApplicationTests.java,其中pom.xml具體內容以下:

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xiaobaiai</groupId>
    <artifactId>test_02_helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test_02_helloworld</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>複製代碼

一樣地咱們把下面代碼複製到Test02HelloworldApplication.java中(注意咱們的類名改了,不是Test01了):

package com.xiaobaiai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
@Controller
public class Test02HelloworldApplication {
    @RequestMapping("/")
    @ResponseBody
    public String index() {
        return "Hello World!";
    }
    public static void main(String[] args) {
        SpringApplication.run(Test02HelloworldApplication.class, args);
    }
}複製代碼

最後點擊Run,到瀏覽器中輸入http://localhost:8080回車可看到輸出Hello World!

3.3 基於Spring Boot CLI建立項目

上一篇中咱們已經介紹過Sping Boot CLI(命令行界面)這個工具了,它可用於快速使用Spring進行原型設計。使咱們能夠運行Groovy腳本,接下來咱們實際操做一下。

3.3.1 安裝Spring Boot CLI工具

從Spring軟件存儲庫下載Spring CLI發行版,選擇你工做的平臺版本,這裏選擇了spring-boot-cli-2.2.0.RELEASE-bin.zip Windows版本:

下載好後,解壓,而後配置好環境變量,則就安裝成功,驗證是否安裝並配置好:

# 查看spring cli版本
$ spring --version
Spring CLI v2.2.0.RELEASE
# 查看spring全部幫助
$ spring --help
# 查看spring run命令幫助
$ spring help run
# 查看spring init命令幫助
$ spring help init
# 查看全部支持的dependencies,支持的工程類型(Project types,默認工程類型爲marven-project)
$ spring init --list複製代碼

$ spring init --list
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
:: Service capabilities ::  https://start.spring.io

Supported dependencies
+--------------------------------------+--------------------------------------------------------------+-------------------------------+
| Id                                   | Description                                                  | Required version              |
+--------------------------------------+--------------------------------------------------------------+-------------------------------+
......
| activemq                             | Spring JMS support with Apache ActiveMQ 'Classic'.           |                               |
| web                                  | Build web, including RESTful, applications using Spring MVC. |                               |
|                                      | Uses Apache Tomcat as the default embedded container.        |                               |
......
+--------------------------------------+--------------------------------------------------------------+-------------------------------+

Project types (* denotes the default)
+-----------------+------------------------------------------+-----------------------------+
| Id              | Description                              | Tags                        |
+-----------------+------------------------------------------+-----------------------------+
| gradle-build    | Generate a Gradle build file.            | build:gradle,format:build   |
| gradle-project  | Generate a Gradle based project archive. | build:gradle,format:project |
| maven-build     | Generate a Maven pom.xml.                | build:maven,format:build    |
| maven-project * | Generate a Maven based project archive.  | build:maven,format:project  |
+-----------------+------------------------------------------+-----------------------------+

Parameters
+-------------+------------------------------------------+------------------------------+
| Id          | Description                              | Default value                |
+-------------+------------------------------------------+------------------------------+
| artifactId  | project coordinates (infer archive name) | demo                         |
| bootVersion | spring boot version                      | 2.2.0.RELEASE                |
| description | project description                      | Demo project for Spring Boot |
| groupId     | project coordinates                      | com.example                  |
| javaVersion | language level                           | 1.8                          |
| language    | programming language                     | java                         |
| name        | project name (infer application name)    | demo                         |
| packageName | root package                             | com.example.demo             |
| packaging   | project packaging                        | jar                          |
| type        | project type                             | maven-project                |
| version     | project version                          | 0.0.1-SNAPSHOT               |
+-------------+------------------------------------------+------------------------------+複製代碼

3.3.2 使用Spring Boot CLI工具建立Hell World應用

接下來,咱們直接使用Spring Boot CLI工具建立上述咱們的Hello World WEB應用。

# 建立項目name: test_03_helloworld
# groupId: com.xiaobaiai
# artifactId: test_03_helloworld
# language: java/groovy/kotlin
# boot-version: 2.2.0
# 構建工具類型: marven-project/marven-build/gradle-project/gradle-build
# 依賴項(dependencies):web
# java-version: java(jdk)版本
# --package-name: 包名
# --packaging:打包方式jar/war
# --extract: 不加這個參數則建立出來的項目就是已經壓縮過的,跟用Spring Initializr Website建立出來的同樣
# 最後一個test_03_helloworld即指定目標生成目錄
$ mkdir test_03_helloworld
$ cd test_03_helloworld
$ spring init -n test_03_helloworld -g com.xiaobaiai -a test_03_helloworld -l java -b 2.2.0.RELEASE -t maven-project -d web --extract -j 11 --package-name com.xiaobaiai --extract test_03_helloworld複製代碼

💡 spring run命令只是針對Groovy語言的。

建立完成後,其實跟上述兩種方式建立出來的工程是同樣的,而後一樣地,咱們去修改src/main/java/com/xiaobaiai/Test03HelloworldApplication.java這個文件,添加同樣的內容,這裏就不貼代碼了(可使用文本編輯器如Vim/VS Code/Notepad++/Atom/Subline2等等)。

.
├── HELP.md
├── list
│   ├── HELP.md
│   ├── mvnw
│   ├── mvnw.cmd
│   ├── pom.xml
│   └── src
│       ├── main
│       └── test
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   └── resources
    └── test
        └── java複製代碼

💡 用Spring Boot CLI工具建立出來生成的工程文件默認是在當前文件夾中,若是加了--extract參數,則全部文件都解壓出來,所以須要預先創建一個工程目錄再執行建立命令。固然也能夠指定生成文件夾,則會建立項目的時候建立該文件夾並將項目文件都生成到該文件夾中。

💡 另外還可使用SDKMAN管理各類二進制SDK的多個版本,包括Groovy和Spring Boot CLI,具體的能夠去官方文檔瞭解。

接下來就是如何編譯了。spring cli針對不一樣類型語言的WEB應用編譯方式是不同的,若是咱們建立了Groovy語言類型的項目,那麼只須要用到spring run組合命令就能夠了,可是這裏選擇了java語言類型,則須要結合mvn(marven的命令行工具)和java(jdk的命令行工具)了。首先確保這兩個命令已經配置好了環境變量。

而後到項目根目錄執行:

# spring-boot:run爲Spring Boot Maven Plugin插件所支持,還有如spring-boot:repackage/spring-boot:start/spring-boot:stop/spring-boot:build-info。
$ mvn spring-boot:run複製代碼

最後到瀏覽器中輸入http://localhost:8080回車可看到輸出Hello World!

3.4 各建立項目方式比較

  • 使用CLI工具建立大項目仍是優勢麻煩的,只是運行Groovy還能夠選擇一下
  • 使用SPring Initializr工具方便快速

4 Spring Boot應用是如何工做的?

上面是一個簡單的WEB應用,一一講述了幾種建立方式,並在瀏覽器中輸出了Hello World!,那麼整個應用是怎麼運做的呢?這一節咱們詳細地來剖析下。

4.1 pom.xml

4.1.1 spring-boot-starter-parent

pom.xml是整個項目的核心配置文件,Marven的POM文件之間具備集成性,下面這段代碼就表示POM文件繼承自groupIdorg.springframework.bootartifactIdspring-boot-starter-parentversion2.2.0.RELEASE的POM文件。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.0.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>複製代碼

spring-boot-starter-parent項目是一個特殊的啓動程序項目,爲咱們的應用程序提供默認配置,並提供完整的依賴關係樹以快速構建咱們的Spring Boot項目。它還爲Maven插件提供了默認配置,例如maven-failsafe-pluginmaven-jar-pluginmaven-surefire-pluginmaven-war-plugin。咱們能夠找到spring-boot-starter-parent-2.2.0.RELEASE.pom具體查看,如Windows系統中,該文件在C:Users{your username}.m2repositoryorgspringframeworkbootspring-boot-starter-parent2.2.0.RELEASE`路徑下。 Linux平臺在用戶目錄~/.m2/repository/org/springframeworkbootspring-boot-starter-parent2.2.0.RELEASE`路徑下。打開該文件後,咱們能夠看到spring-boot-starter-parent-2.2.0.RELEASE.pom又依賴了spring-boot-dependencies項目,這個文件裏面定義了大部分底層依賴軟件的版本號以及咱們上一節介紹的Spring boot核心模塊,如spring-boot-actuator等。咱們能夠從這個連接獲取spring-boot-starter-parent的最新版本search.maven.org/classic/#se…

4.1.2 spring-boot-starter-web

再到咱們的應用這一層,咱們依賴了spring-boot-starter-webspring-boot-starter-test(能夠作單元測試)兩個依賴。咱們能夠經過STS能夠看到兩個依賴裏又包含了哪些依賴,如spring-boot-starter-web裏面依賴了tomcat(實際用的是spring boot內嵌的tomcat)、spring-webspring-webmvc等。有了這些依賴其實就構成了咱們實現一個Web Server的基礎。

另外,添加了父級依賴模塊(spring-boot-starter-parent)後,在應用中添加其餘依賴,咱們是不須要指定版本了,因此的依賴版本已經在父級依賴中獲得了管理(固然,咱們也能夠獨立指定版本)。如:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>複製代碼

4.1.3 dependencyManagement標籤自定義父級依賴以及其餘屬性自定義

咱們能夠定義本身的一套父級版本依賴嗎?固然是能夠的,咱們只須要定義 標記裏內容就能夠了,相似spring-boot-dependencies的POM文件裏所示同樣:

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot</artifactId>
        <version>2.2.0.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-test</artifactId>
        <version>2.2.0.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-test-autoconfigure</artifactId>
        <version>2.2.0.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
        <version>2.2.0.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator-autoconfigure</artifactId>
        <version>2.2.0.RELEASE</version>
        
        ......
        
    </dependencies>
</dependencyManagement>複製代碼

爲了自定義父級依賴中其餘屬性(配置),咱們能夠在相應位置從新去聲明配置相關值,spring-boot-starter-parent經過其父級spring-boot-dependencies依賴使用屬性來配置全部依賴項版本,Java版本和Maven插件版本等。所以,咱們只需更改相應的屬性便可自定義控制這些配置。好比咱們想更改tomcat的版本,只須要在spring-boot-dependencies的POM文件中對應位置修改以下代碼:

<properties>
    ......
    <tomcat.version>9.0.27</tomcat.version>
    ......
</properties>
複製代碼

4.1.4 自定義父級依賴

對於添加指定的父級依賴,而不是spring-boot-starter-parent,咱們能夠徹底自定義配置咱們全部的依賴,那麼咱們就須要配置相似spring-boot-starter-parent全部相關的內容,包括版本以及相關屬性配置等。

4.1.5 Spring Boot Marven插件

pom.xml中還有這麼一段代碼:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>複製代碼

上面的配置就是Spring Boot Maven插件,Spring Boot Maven插件提供了許多方便的功能:

  • 把項目打包成一個可執行的超級JAR(uber-JAR),包括把應用程序的全部依賴打入JAR文件內,併爲JAR添加一個描述文件,其中的內容能讓你用java -jar來運行應用程序。
  • 搜索public static void main()方法來標記爲可運行類。

4.2 Spring Boot 註解(annotations)與應用入口

4.2.1 註解(annotations)

在咱們實現的簡單Hello World Web項目中,咱們使用了幾個註解,如代碼中所示的SpringBootApplicationController

@SpringBootApplication
@Controller
public class Test02HelloworldApplication {
    @RequestMapping("/")
    @ResponseBody
    public String index() {
        return "Hello World!";
    }
    public static void main(String[] args) {
        SpringApplication.run(Test02HelloworldApplication.class, args);
    }

}複製代碼

咱們能夠直接看到SpringBootApplication類中是什麼內容,具體作了啥?它的定義以下:

@Target(ElementType.TYPE) // 元註解,指定了註解運用的地方,註解就被限定了運用的場景,此處限定爲能夠給一個類型進行註解,好比類、接口、枚舉
@Retention(RetentionPolicy.RUNTIME)  // 元註解, 註解能夠保留到程序運行的時候,它會被加載進入到 JVM 中,因此在程序運行時能夠獲取到它們
@Documented // 元註解,將註解中的元素包含到 Javadoc 中去
@Inherited // 元註解,超類被 @Inherited 註解過的註解進行註解的話,那麼若是它的子類沒有被任何註解應用的話,那麼這個子類就繼承了超類的註解。
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
@ConfigurationPropertiesScan
public @interface SpringBootApplication {
    ......
}複製代碼

裏面又有三個重要的註解:

1) @SpringBootConfiguration

該註解向類添加@Configuration註解,該註解將類標記爲應用程序上下文的Bean定義的源。

2) @EnableAutoConfiguration

這告訴Spring Boot經過基於類路徑設置,其餘bean和各類屬性設置添加bean,從而基於pom.xml中添加的依賴關係自動配置重要的bean定義。

3) @ComponentScan

該註解告訴Spring boot掃描基礎包,查找其餘的bean/組件,並對其進行配置。

4) @Controller : 該註解指定了當前類Test02HelloworldApplication充當MVC中控制器做用,調度程序掃描帶此類註解的類以查找映射的方法,並檢測@RequestMapping註解。

5)@RequestMapping : 你可使用@RequestMapping註解將URL(例如/appointments)映射到整個類或特定的處理方法上。一般,類級別的註解將特定的請求路徑(或路徑模式)映射到表單控制器上,其餘方法級別的註解使特定的HTTP請求方法(GET、POST等)的主映射範圍變窄,或一個HTTP請求參數條件。下面是一個Controller + RequestMapping的示例:

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private final AppointmentBook appointmentBook;

    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

    @RequestMapping(value="/{day}", method = RequestMethod.GET)
    public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
        return appointmentBook.getAppointmentsForDay(day);
    }

    @RequestMapping(value="/new", method = RequestMethod.GET)
    public AppointmentForm getNewForm() {
        return new AppointmentForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String add(@Valid AppointmentForm appointment, BindingResult result) {
        if (result.hasErrors()) {
            return "appointments/new";
        }
        appointmentBook.addAppointment(appointment);
        return "redirect:/appointments";
    }
}複製代碼

在類級別上,若是沒有@RequestMapping,想URL路徑都是絕對的,而不是相對的,如咱們Hello World WEB項目裏代碼所示。而上面的示例都是相對appointments路徑。

4.2.2 應用入口及應用配置

在上一節中咱們也提到了SpringApplication類的做用,只是沒有實際項目來體會,這一節有了Hello World程序做爲示例,咱們再次來總結它的做用,進一步加深理解:

  • @SpringBootApplication是Sprnig Boot項目的核心註解,主要目的是開啓自動配置,包括建立上下文內容,刷新應用上下文,並加載全部單例Bean
  • 在大多數狀況下,能夠直接從主方法中調用靜態run(Class, String [])方法來引導應用程序
  • 能夠在應用運行以前建立和定製SpringApplication實例,如:
SpringApplication springApplication = new SpringApplication(SpringbootActionApplication.class);
// 關閉應用啓動時的Banner,以下:
//  .   ____          _            __ _ _
// /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
//( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
// \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
//  '  |____| .__|_| |_|_| |_\__, | / / / /
// =========|_|==============|___/=/_/_/_/
// :: Spring Boot ::        (v2.2.0.RELEASE)
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run(args);複製代碼

在修改應用程序默認配置上,咱們還能夠經過src/main/resources/application.properties這個文件來配置。裏面內容默認爲空。常見配置有:

# 指定應用名(該名字在Spring Cloud應用中會被註冊爲服務名)
spring.application.name=hello
# 關閉Banner
spring.main.banner-mode=off
# 修改WEB端口8080爲8081
server.port = 8081
# 修改日誌級別和中控臺日誌保存文件路徑
# 全部文件日誌打印級別爲WARN
logging.level.root=WARN
# 指定包或具體類打印日誌級別, 如logging.level.com.xiaobaiai=DEBUG
logging.level.{some.package.path}=DEBUG
# 默認日誌都會打印到控制檯,你能夠設定打印到文件,即直接指定路徑和文件名
logging.file=\path_to\logfile.log
# 也能夠只指定路徑,默認爲spring.log
logging.file.path=C:\\Work\\sts4\\test_02_helloworld\\logs
# 自定義屬性值,而後在應用程序中經過@Value註解來賦值,
# @Value(value=」${com.xiaobaiai.name}」)
# private String name;
com.xiaobaiai.name="小白AI"複製代碼

固然咱們還能夠在配置參數與配置參數之間進行引用,還可使用指定配置參數文件,或者經過定義專用類來導入配置,這裏就不展開了。

5 總結

這一節內容有點長,可是總的來講就是講述了三種方式去建立一個Hello World WEB 項目,而後對這個WEB項目從pom.xml文件開始進行了分析,講述了父級依賴,以及應用依賴和具體的版本依賴是如何實現的,最後對Spring Boot的應用入口和重要的幾個註解也進行了講解。完成這些,咱們如今基本上對Spring Boot應用有了基本的瞭解了,接下來咱們繼續。

6 參考資料

  • https://www.thymeleaf.org/
  • https://howtodoinjava.com/spring-boot/spring-boot-tutorial-with-hello-world-example/
  • https://www.journaldev.com/8195/spring-boot-cli-setup-and-helloworld-example
  • https://www.dev2qa.com/spring-boot-hello-world-example-in-sts/
  • https://start.spring.io/
  • https://spring.io/tools
  • https://maven.apache.org/guides/mini/guide-naming-conventions.html
  • https://docs.spring.io/spring-boot/docs/current/maven-plugin/
  • https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-cli.html
  • https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/
  • https://www.cnblogs.com/acm-bingzi/p/mavenSpringBootPlugin.html
  • https://stackoverflow.com/questions/42024546/use-of-spring-boot-maven-plugin
  • https://www.tianmaying.com/tutorial/project-based-on-spring-boot spring-boot初探
  • https://tengj.github.io/2017/02/26/springboot1/ 解析pom.xml 父級依賴
  • https://dzone.com/articles/hello-world-program-spring-boot RequestMapping Controller 做用
  • https://howtodoinjava.com/spring-boot/spring-boot-tutorial-with-hello-world-example/ 各類Spring boot示例
  • https://juejin.im/post/5db24ed5f265da4d3f44abf1 關閉banner
  • https://www.cnblogs.com/zwwhnly/p/11572302.html spring mvc經常使用註解
  • https://www.journaldev.com/8195/spring-boot-cli-setup-and-helloworld-example
  • https://spring.io/guides/gs/spring-boot/#addunit_tests 單元測試
  • https://www.baeldung.com/spring-boot-starter-parent
  • https://search.maven.org/classic/
  • https://blog.csdn.net/shengzhu1/article/details/81271409
  • https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-controller
  • http://tengj.top/2017/02/28/springboot2/

本文屬於原創,轉載註明出處,歡迎關注CSDNfreeape或微信小程序小白AI博客 微信公衆號小白AI或者網站 xiaobaiai.net

相關文章
相關標籤/搜索