Spring Boot入門


一、簡介

使用 Spring Boot 可以很容易地創建出能直接運行的獨立的、生產級別的基於 Spring 的應用。我們對 Spring 平台和第三方類庫有自己的考慮,因此您可以從最基本的開始。大多數 Spring Boot 應用只需要很少的 Spring 配置。

您可以使用 Spring Boot 來創建一個可以使用 java -jar 命令來運行或者基於傳統的 war 包部署的應用程序。我們還提供了一個用於運行 spring scripts 的命令行工具。

我們的主要目標是:

  • 為所有 Spring Boot 開發提供一個更快、更全面的入門體驗。
  • 堅持自我雖好,但當需求出現偏離,您需要能迅速擺脫出來。
  • 提供大量非功能性特性相關項目(例如:內嵌服務器、安全、指標、健康檢查、外部配置)。
  • 絕對沒有代碼生成,也不要求 XML 配置。

Spring

二、創建可執行 jar

要創建可執行 jar,我們需要將 spring-boot-maven-plugin 添加到 pom.xml 文件中。在 dependencies 下方插入以下配置:

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

三、使用Spring Boot

3.1 Maven

Maven 用戶可以繼承 spring-boot-starter-parent 項目以獲取合適的默認值,父項目提供了以下功能:

  • Java 1.8 作為默認編譯器級別。
  • 源代碼使用 UTF-8 編碼。
  • 依賴管理部分繼承自 spring-boot-dependencies 的 POM,允許您省略常見依賴的 標簽。
  • 合理的資源過濾。
  • 合適的插件配置(exec plugin、Git commit ID、shade)。
  • 針對 application.properties 和 application.yml 資源的合理過濾,包括特定 profile 的文件(例如 application-foo.properties 和 application-foo.yml)
3.1.1 繼承Starter Parent

要將項目配置繼承 spring-boot-starter-parent,只需要按以下方式設置 parent:

<!-- 從 Spring Boot 繼承默認配置 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>

3.2、Starter

Starter 是一組慣例依賴描述資源,可以包含在應用中。從 starter 中,您可以獲得所需的所有 Spring 和相關技術的一站式支持,無須通過示例代碼和復制粘貼來獲取依賴。比如,如果您要使用 Spring 和 JPA 進行數據庫訪問,那么只需要在項目中包含 spring-boot-starter-data-jpa 依賴項即可。

Spring Boot 在 org.springframework.boot group 下提供了以下應用 starter:

3.2.1 Spring Boot 應用類 Starter
名稱 描述
spring-boot-starter 核心 starter,包含自動配置支持、日志和 YAML
spring-boot-starter-activemq 提供 JMS 消息支持,使用 Apache ActiveMQ
spring-boot-starter-amqp 提供 Spring AMQP 與 Rabbit MQ 支持
spring-boot-starter-aop 提供 Spring AOP 與 AspectJ 面向切面編程支持
spring-boot-starter-artemis 提供 JMS 消息服務支持,使用 Apache Artemis
spring-boot-starter-batch 提供 Spring Batch 支持
spring-boot-starter-cache 提供 Spring Framework 緩存支持
spring-boot-starter-cloud-connectors 使用 Spring Cloud Connectors 簡單連接到類似 Cloud Foundry 和 Heroku 等雲平台
spring-boot-starter-data-cassandra 提供對 Cassandra 分布式數據庫和 Spring Data Cassandra 的支持
spring-boot-starter-data-cassandra-reactive 提供對 Cassandra 分布式數據庫和 Spring Data Cassandra Reactive 的支持
spring-boot-starter-data-couchbase 提供對 Couchbase 面向文檔數據庫和 Spring Data Couchbase 的支持
pring-boot-starter-data-couchbase-reactive 提供對 Couchbase 面向文檔數據庫和 Spring Data Couchbase Reactive 的支持
spring-boot-starter-data-elasticsearch 提供對 Elasticseach 搜索與分析引擎和 Spring Data Elasticsearch 的支持
spring-boot-starter-data-jpa 供 Spring Data JPA 與 Hibernate 的支持
spring-boot-starter-data-mongodb 提供對 MongoDB 面向文檔數據庫和 Spring Data MongoDB 的支持
spring-boot-starter-data-mongodb-reactive 提供對 MongoDB 面向文檔數據庫和 Spring Data MongoDB Reactive 的支持
spring-boot-starter-data-neo4j 提供對 Neo4j 圖數據庫與 SPring Data Neo4j 的支持
spring-boot-starter-data-redis 提供對 Redis 鍵值數據存儲、Spring Data Redis 和 Lettuce 客戶端的支持
spring-boot-starter-data-redis-reactive 提供對 Redis 鍵值數據存儲、Spring Data Redis Reactive 和 Lettuce 客戶端的支持
spring-boot-starter-data-rest 提供使用 Spring Data REST 通過 REST 暴露 Spring Data 資源庫的支持
spring-boot-starter-freemarker 提供使用 Freemakrer 視圖構建 MVC web 應用的支持
spring-boot-starter-jdbc 提供 JDBC 與 Tomcat JDBC 連接池的支持
spring-boot-starter-json 提供了讀寫 json 的支持
spring-boot-starter-mail 提供使用 Java Mail 與 Spring Framework 的郵件發送支持
spring-boot-starter-security Spring Security 支持
spring-boot-starter-test 供包含了 JUnit、Hamcrest 與 Mockito 類庫的 Spring Boot 單元測試支持
spring-boot-starter-thymeleaf 提供使用 Thymeleaf 視圖構建 MVC web 應用的支持
spring-boot-starter-validation 提供 Hibernate Validator 與 Java Bean Validation 的支持
spring-boot-starter-web 提供使用 Spring MVC 構建 web(包含 RESTful)應用的支持,使用 Tomcat 作為默認嵌入式容器
spring-boot-starter-web-services Spring Web Services 支持
spring-boot-starter-webflux 提供使用 Spring Framework 的 Reactive Web 支持構建 WebFlux 應用的支持
spring-boot-starter-websocket 提供使用 Spring Framework 的 WebSocket 支持構建 WebSocket 應用的支持
3.2.2 Spring Boot技術類 starter
名稱 描述
spring-boot-starter-jetty 使用 Jetty 作為嵌入式 servlet 容器。可代替 spring-boot-starter-tomcat
spring-boot-starter-log4j2 使用 Log4j2 作為日志組件。可代替 spring-boot-starter-logging
spring-boot-starter-logging 使用 Logback 作為日志組件,此 starter 為默認的日志 starter
spring-boot-starter-reactor-netty 使用 Reactor Netty 作為內嵌響應式 HTTP 服務器
spring-boot-starter-tomcat 使用 Tomcat 作為嵌入式 servlet 容器,此為 spring-boot-starter-web 默認的 servlet 容器 starter
spring-boot-starter-undertow 使用 Undertow 作為嵌入式 servlet 容器,可代替 spring-boot-starter-tomcat

3.3 使用@SpringBooApplication注解

很多 Spring Boot 開發者總是使用 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 注解標記在主類上。由於 這些注解經常一起使用。Spring Boot 提供了一個更方便的 @SpringBootApplication 注解可用來替代這個組合。

@SpringBootApplication 注解相當於使用 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 及他們的默認屬性:

package com.example.myapplication;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // 相當於使用 @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

四、SpringBoot 特性

4.1 自定義banner

可以通過在 classpath 下添加一個 banner.txt 文件,或者將 spring.banner.location 屬性指向該文件的位置來更改啟動時打印的 banner。如果文件采用了非 UTF-8 編碼,您可以設置 spring.banner.charset 來解決。除了文本文件,您還可以將 banner.gif、banner.jpg 或者 banner.png 圖片文件添加到 classpath 下,或者設置 spring.banner.image.location 屬性。指定的圖片將會被轉換成 ASCII 形式並打印在 banner 文本上方。

變量 描述
${application.version} 您的應用版本號,聲明在 MANIFEST.MF 中。例如,Implementation-Version: 1.0 將被打印為 1.0。
${application.formatted-version} 您的應用版本號,聲明在 MANIFEST.MF 中,格式化之后打印(用括號括起來,以 v 為前綴),例如 (v1.0)。
${spring-boot.version} 您使用的 Spring Boot 版本。例如 2.1.1.RELEASE.。
${spring-boot.formatted-version} 您使用的 Spring Boot 版本格式化之后顯示(用括號括起來,以 v 為前綴)。例如 (v2.1.1.RELEASE)。
$ {Ansi.NAME}(或${AnsiColor.NAME}、$ {AnsiBackground.NAME}、$ {AnsiStyle.NAME}) 其中 NAME 是 ANSI 轉義碼的名稱。有關詳細信息,請參閱 AnsiPropertySource。
${application.title} 您的應用標題,聲明在 MANIFEST.MF 中,例如 Implementation-Title: MyApp 打印為 MyApp。

注意

YAML 將 off 映射為 false,因此如果要禁用應用程序 banner,請確保屬性添加引號。

spring:
    main:
        banner-mode: "off"

4.2 外部化配置

Spring Boot 可以讓您的配置外部化,以便可以在不同環境中使用相同的應用程序代碼。您可以使用 properties 文件、YAML 文件、環境變量或者命令行參數來外部化配置。可以使用 @Value 注解將屬性值直接注入到 bean 中,可通過 Spring 的 Environment 訪問,或者通過 @ConfigurationProperties 綁定到結構化對象。

Spring Boot 使用了一個非常特別的 PropertySource 指令,用於智能覆蓋默認值。屬性將按照以下順序處理:

  1. 在您的主目錄(當 devtools 被激活,則為 ~/.spring-boot-devtools.properties )中的 Devtools 全局設置屬性。
  2. 在測試中使用到的 @TestPropertySource 注解。
  3. 在測試中使用到的 properties 屬性,可以是 @SpringBootTest 和用於測試應用程序某部分的測試注解。
  4. 命令行參數。
  5. 來自 SPRING_APPLICATION_JSON 的屬性(嵌入在環境變量或者系統屬性【system propert】中的內聯 JSON)。
  6. ServletConfig 初始化參數。
  7. ServletContext 初始化參數。
  8. 來自 java:comp/env 的 JNDI 屬性。
  9. Java 系統屬性(System.getProperties())。
  10. 操作系統環境變量。
  11. 只有 random.* 屬性的 RandomValuePropertySource。
  12. 在已打包的 jar 外部的指定 profile 的應用屬性文件(application-{profile}.properties 和 YAML 變量)。
  13. 在已打包的 jar 內部的指定 profile 的應用屬性文件(application-{profile}.properties 和 YAML 變量)。
  14. 在已打包的 jar 外部的應用屬性文件(application.properties 和 YAML 變量)。
  15. 在已打包的 jar 內部的應用屬性文件(application.properties 和 YAML 變量)。
  16. 在 @Configuration 類上的 @PropertySource 注解。
  17. 默認屬性(使用 SpringApplication.setDefaultProperties 指定)。

舉個例子,假設開發的 @Component 使用了 name 屬性,可以這樣:

import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;

@Component
public class MyBean {

    @Value("${name}")
    private String name;

    // ...

}

在您的應用程序的 classpath 中(比如在 jar 中),您可以有一個 application.properties,它為 name 提供了一個合適的默認屬性值。當在新環境中運行時,您可以在 jar 外面提供一個 application.properties 來覆蓋 name。對於一次性測試,您可以使用命令行指定形式啟動(比如 java -jar app.jar --name="Spring")。

4.3 @ConfigurationProperties驗證

只要使用了 Spring 的 @Validated 注解,Spring Boot 就會嘗試驗證 @ConfigurationProperties 類。您可以直接在配置類上使用 JSR-303 javax.validation 約束注解。為此,請確保 JSR-303 實現在 classpath 上,然后將約束注解添加到字段上,如下所示:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

雖然綁定時也會驗證嵌套屬性,但最好的做法還是將關聯字段注解上 @Valid。這可確保即使未找到嵌套屬性也會觸發驗證。以下示例基於前面的 AcmeProperties 示例:

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

    @NotNull
    private InetAddress remoteAddress;

    @Valid
    private final Security security = new Security();

    // ... getters and setters

    public static class Security {

        @NotEmpty
        public String username;

        // ... getters and setters

    }

}

您還可以通過創建一個名為 configurationPropertiesValidator 的 bean 定義來添加自定義 Spring Validator。應該將 @Bean 方法聲明為 static。配置屬性驗證器在應用程序生命周期的早期創建,將 @Bean 方法聲明為 static 可以無需實例化 @Configuration 類來創建 bean。這樣做可以避免早期實例化可能導致的意外問題。這里有一個屬性驗證示例,講解了如何設置。

4.4 @ConfigurationProperties 與 @Value 對比

@Value 注解是核心容器功能,它不提供與類型安全配置屬性相同的功能。下表總結了 @ConfigurationProperties 和 @Value 支持的功能:

功能 @ConfigurationProperties @Value
寬松綁定
元數據支持
SpEL 表達式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM