第 04 章 微服務框架(4.1) spring boot

Spring 簡史

Spring 1.x 時代

在 Spring1.x 時代,都是通過 xml 文件配置 bean,隨着項目的不斷擴大,需要將 xml 配置分放到不同的配置文件中,需要頻繁的在 java 類和 xml 配置文件中切換。

Spring 2.x 時代

隨着 JDK 1.5 帶來的註解支持,Spring2.x 可以使用註解對 Bean 進行申明和注入,大大的減少了 xml 配置文件,同時也大大簡化了項目的開發。

那麼,問題來了,究竟是應該使用 xml 還是註解呢?

最佳實踐:

應用的基本配置用 xml,比如:數據源、資源文件等
業務開發用註解,比如:Service 中注入 bean 等
Spring 3.x 時代

從 Spring3.x 開始提供了 Java 配置方式,使用 Java 配置方式可以更好的理解你配置的 Bean,現在我們就處於這個時代,並且 Spring4.x 和 Spring boot 都推薦使用 java 配置的方式。

Spring 5.x 時代

Spring5.x 是 Java 界首個支持響應式的 Web 框架,是 Spring 的一個重要版本,距離 Spring4.x 差不多四年。在此期間,大多數增強都是在 SpringBoot 項目中完成的,其最大的亮點就是提供了完整的端到端響應式編程的支持(新增 Spring WebFlux 模塊)。

Spring WebFlux 同時支持使用舊的 Spring MVC 註解聲明 Reactive Controller。和傳統的 MVC Controller 不同,Reactive Controller 操作的是 非阻塞 的 ServerHttpRequest 和 ServerHttpResponse,而不再是 Spring MVC 裏的 HttpServletRequest 和 HttpServletResponse。

至此也代表着 Java 正式迎來了響應式異步編程的時代。

Spring Boot 簡介

隨着動態語言的流行 (Ruby、Groovy、Scala、Node.js),Java 的開發顯得格外的笨重:繁多的配置、低下的開發效率、複雜的部署流程以及第三方技術集成難度大。

在上述環境下,Spring Boot 應運而生。它使用“習慣優於配置”(項目中存在大量的配置,此外還內置了一個習慣性的配置,讓你無需手動進行配置)的理念讓你的項目快速的運行起來。使用 Spring Boot 很容易創建一個獨立運行(運行 Jar,內嵌 Servlet 容器)準生產級別的基於 Spring 框架的項目,使用 Spring Boot 你可以不用或者只需很少的 Spring 配置。

Spring Boot 優缺點

優點

快速構建項目
對主流開發框架的無配置集成
項目可獨立運行,無需外部依賴 Servlet 容器
提供運行時的應用監控
極大地提高了開發、部署效率
與雲計算的天然集成
缺點

版本迭代速度很快,一些模塊改動很大
由於不用自己做配置,報錯時很難定位
網上現成的解決方案比較少

第一個 Spring Boot 應用程序

這裏我們使用 Intellij IDEA 來新建一個 Spring Boot 項目。

打開 IDEA -> New Project -> Spring Initializr
這裏寫圖片描述
填寫項目信息
這裏寫圖片描述
選擇 Spring Boot 版本及 Web 開發所需的依賴
這裏寫圖片描述
保存項目到指定目錄
這裏寫圖片描述
工程目錄結構

創建完成後的工程目錄結構如下:
│ .gitignore
│ pom.xml


└─src
├─main
│ ├─java
│ │ └─com
│ │ └─funtl
│ │ └─hello
│ │ └─spring
│ │ └─boot
│ │ HelloSpringBootApplication.java
│ │
│ └─resources
│ │ application.properties
│ │
│ ├─static
│ └─templates
└─test
└─java
└─com
└─funtl
└─hello
└─spring
└─boot
HelloSpringBootApplicationTests.java
.gitignore:Git 過濾配置文件
pom.xml:Maven 的依賴管理配置文件
HelloSpringBootApplication.java:程序入口
resources:資源文件目錄
static: 靜態資源文件目錄
templates:模板資源文件目錄
application.properties:Spring Boot 的配置文件,實際開發中會替換成 YAML 語言配置(application.yml)
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.funtl</groupId>
    <artifactId>hello-spring-boot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>hello-spring-boot</name>
    <description></description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</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>
        </dependency>
    </dependencies>

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

</project>

parent:繼承了 Spring Boot 的 Parent,表示我們是一個 Spring Boot 工程
spring-boot-starter-web:包含了 spring-boot-starter 還自動幫我們開啓了 Web 支持
功能演示

我們創建一個 Controller 來演示一下 Spring Boot 的神奇功能

package com.funtl.hello.spring.boot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String sayHi() {
        return "Hello Spring Boot";
    }
}

啓動 HelloSpringBootApplication 的 main() 方法,瀏覽器訪問 http://localhost:8080 可以看到:

Hello Spring Boot
神奇之處

沒有配置 web.xml
沒有配置 application.xml,Spring Boot 幫你配置了
沒有配置 application-mvc.xml,Spring Boot 幫你配置了
沒有配置 Tomcat,Spring Boot 內嵌了 Tomcat 容器

Spring Boot 單元測試

Spring Boot 單元測試

主要是通過 @RunWith 和 @SpringBootTest 註解來開啓單元測試功能

package com.funtl.hello.spring.boot;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloSpringBootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloSpringBootApplicationTests {

    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @Test
    public void contextLoads() {
        ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
        assertThat(response.getBody(), equalTo("Hello Spring Boot"));
    }

}

運行它會先啓動 Spring Boot 工程,再啓動單元測試

Spring Boot 常用配置

Spring Boot 常用配置

本章節主要介紹一下 Spring Boot 中的一些常用配置,比如:自定義 Banner、配置日誌、關閉特定的自動配置等。

Spring Boot 自定義 Banner

在 Spring Boot 啓動的時候會有一個默認的啓動圖案

. _ _ _
/\ / _ ()_ _ _ _ \ \ \ \
( ( )___ | ‘_ | ‘| | ‘ \/ _` | \ \ \ \
\/ _)| |)| | | | | || (| | ) ) ) )
’ |_| .|| ||| |_, | / / / /
=========||==============|__/=///_/
:: Spring Boot :: (v1.5.8.RELEASE)
我們在 src/main/resources 目錄下新建一個 banner.txt

通過 http://patorjk.com/software/taag 網站生成字符串,將網站生成的字符複製到 banner.txt 中

再次運行這個程序

               _ooOoo_
              o8888888o
              88" . "88
              (| -_- |)
              O\  =  /O
           ____/`---'\____
         .'  \|     |//  `.
        /  \|||  :  |||//  \
       /  _||||| -:- |||||-  \
       |   | \\\  -  /// |   |
       | \_|  ''\---/''  |   |
       \  .-\__  `-`  ___/-. /
     ___`. .'  /--.--\  `. . __
  ."" '<  `.___\_<|>_/___.'  >'"".
 | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 \  \ `-.   \_ __\ /__ _/   .-` /  /

======-.____-.__/_.-____.-'======
=—=’
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
佛祖保佑 永無BUG

Spring Boot 配置文件

Spring Boot 配置文件

Spring Boot 項目使用一個全局的配置文件 application.properties 或者是 application.yml,在 resources 目錄下或者類路徑下的 /config 下,一般我們放到 resources 下。

修改 Tomcat 的端口爲 9090,並將默認的訪問路徑 “/“ 修改爲 “boot”,可以在 application.properties 中添加:

server.port=9090
server.context-path=/boot
或在 application.yml 中添加:

server:
port: 9090
context-path: /boot
測試效果:

這裏寫圖片描述

更多配置:https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/html/common-application-properties.html

Spring Boot Starter POM

Starter POM

Spring Boot 爲我們提供了簡化企業級開發絕大多數場景的 starter pom ,只要使用了應用場景所需要的 starter pom ,相關的技術配置將會消除,就可以得到 Spring Boot 爲我們提供的自動配置的 Bean。

官方提供的 starter pom

https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/html/using-boot-build-systems.html#using-boot-starter

Spring Boot 日誌配置

Spring Boot 日誌配置

Spring Boot 對各種日誌框架都做了支持,我們可以通過配置來修改默認的日誌的配置

默認情況下,Spring Boot 使用 Logback 作爲日誌框架

配置日誌文件

logging:
  file: ../logs/spring-boot-hello.log
  level.org.springframework.web: DEBUG

關閉特定的自動配置

關閉特定的自動配置使用 @SpringBootApplication 註解的 exclude 參數即可,這裏以關閉數據源的自動配置爲例

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章