1. 程式人生 > >微服務 SpringBoot 2.0(一):簡單入門構建

微服務 SpringBoot 2.0(一):簡單入門構建

我做好了從入門到放棄的準備,你卻告訴我炒雞簡單 —— Java面試必修

引言

SpringBoot是由Pivotal團隊提供的全新框架,從最根本上來講,Spring Boot就是簡化開發人員從0構建專案的繁瑣步驟,巧妙的封裝了很多外掛模組,讓開發人員不再擔心版本依賴或複雜的三方依賴問題,它能夠被任意專案的構建系統所使用。

入門專案

接下來,我們什麼都先不談,本文著重介紹SpringBoot簡單配置與服務搭建,預計花費您5分鐘的閱讀時間,動起來吧,非常非常簡單噢。

工具

SpringBoot版本:2.0.4
開發工具:IDEA 2018
Maven:3.3 9
JDK:1.8

專案快速建立方式一:

首先我們在SPRING INITIALIZR 上建一個簡單專案,並匯入到IDEA中,如下圖:
詳見網址

下一步,匯入到工程

下一步,選擇已有模組

下一步,更改maven變數

下一步,選擇JDK1.8目錄

簡單專案建立完成

專案快速建立方式二(常用):

步驟 File—>New—>Project
手動快速建立

輸入maven資訊

選擇web,下一步

下一步,然後直接完成,選擇new window即可
建立完成,下面我們解析剛剛涉及到的幾個點

工程結構

DemoApplication.java:應用程式啟動入口,可直接Run啟動服務,類似於tomcat的start.sh
DemoApplicationTests.java:Junit測試類,已自動注入載入了SpringBoot容器的上下文
application.properties:配置屬性空檔案,可改為application.yml檔案,SpringBoot都能識別
pom.xml

:maven工程定義檔案,表明該專案的maven座標資訊

疑問解析

  1. 構建專案時為何選擇了Spring Initializr
    答:spring initializr 是Spring 官方提供的一個很好的工具,用來初始化一個Spring boot 的專案
  2. spring initializr有兩種用法。一是在官網建立然後匯入到編輯器,二是直接File->New->Project

SpringBoot 之pom.xml

以下簡稱xml,xml中與普通maven專案的xml無太多差異,如下:
SpringBoot的pom.xml

pom差異解析

差異一. 引入了該parent說明具備了SpringBoot的基本功能,可直接依賴其父工程(SpringBoot)的包,如差異二(無需宣告版本號)

差異二. web應用啟動核心jar,解壓出來裡面除了些依賴什麼都沒有,所以Starter主要用來簡化依賴用的,比如我們之前做MVC時要引入日誌元件,那麼需要去找到log4j的版本,然後引入,現在有了Starter之後,直接用這個之後,log4j就自動引入了,也不用關心版本這些問題,注:若想更改其下某一個jar(如log4j)的版本,則可自行進行升降

差異三. 能夠將Spring Boot應用打包為可執行的jar或war檔案,然後以通常的方式執行Spring Boot應用

獨特實現(不常用)

如果你不想使用spring-boot-starter-parent,或您自己有一套parent依賴標準,您仍然可以通過使用scope = import依賴關係來保持依賴關係管理:

<dependencyManagement>
     <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.0.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

該設定不允許您使用如上所述的屬性(properties)覆蓋各個依賴項,要實現相同的結果,您需要在spring-boot-dependencies項之前的專案的dependencyManagement中新增一個配置,例如,要升級到另一個Spring Data版本系列,您可以將以下內容新增到自己的pom.xml中。

<dependencyManagement>
    <dependencies>
        <!-- Override Spring Data release train provided by Spring Boot -->

        <!--Spring Data版本更改至Kay-SR9 |變更部分  start-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Kay-SR9</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
        <!--注意:需啊喲在spring-boot-dependencies之前加入需更改的   |變更部分 end -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.0.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>


    </dependencies>
</dependencyManagement>

常用依賴模組

Spring Boot提供了很多已封裝好的模組,類似於外掛,拿來即用,大多都是spring-boot-starter-xx風格,如果要用直接引入即可,就像組裝電腦,組裝i3還是裝i5的CPU看你 自己,下面我們隨便舉例幾個:

<!--快速web應用開發-->
<artifactId>spring-boot-starter-web</artifactId>

<!--redis快取服務-->
<artifactId>spring-boot-starter-redis</artifactId>

<!--應用日誌-->
<artifactId>spring-boot-starter-logging</artifactId>

<!--容器層約定和定製-->
<artifactId>spring-boot-starter-jetty</artifactId>
<artifactId>spring-boot-starter-undertow</artifactId>

<!--資料庫訪問-->
<artifactId>spring-boot-starter-jdbc</artifactId>

<!--面向切面-->
<artifactId>spring-boot-starter-aop</artifactId>

<!--應用安全-->
<artifactId>spring-boot-starter-security</artifactId>

應用演示

以我們剛剛新建的DemoApplication.java為例
1.pom.xml檔案加入web服務外掛(呀,是誰這麼聰明,以前弄個springmvc一套下來10來個jar,現在只管一個了)

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 我們直接在註解上面加入@RestController,並且加入一個RequestMapping方法,啟動伺服器之後,我們訪問這個方法即可看到效果
package com.ron.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class DemoApplication {

	@RequestMapping("/index")
	public String index(){
		return "Hello Spring Boot";
	}

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

	}
}
  1. @RestController註解等價於@[email protected]的結合,使用這個註解的類裡面的方法都以json格式輸出
  2. @SpringBootApplication是Sprnig Boot專案的核心註解,主要目的是開啟自動配置。後續講解原理的時候深入介紹。
  3. main方法這是一個標準的Java應用的main的方法,主要作用是作為專案啟動的入口。
run執行

啟動成功

開啟瀏覽器訪問

成功訪問

單元測試場景

找到專案目錄了src/test/下的測試入口,編寫簡單的http請求來測試;使用mockmvc進行,利用MockMvcResultHandlers.print()打印出執行結果。

package com.ron.demo;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

	private MockMvc mvc;
	@Before
	public void setUp() throws Exception {   <!--此處為需要測試的Controller類-->
		mvc = MockMvcBuilders.standaloneSetup(new DemoApplication()).build();
	}

	@Test
	public void contextLoads() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/index").accept(MediaType.APPLICATION_JSON))
				.andExpect(MockMvcResultMatchers.status().isOk())
				.andDo(MockMvcResultHandlers.print())
				.andReturn();

	}

}

直接在DemoApplicationTests 中 Ctrl+Shift+F10執行即可看到如下執行結果,若報錯請仔細檢查@Before方法

控制檯執行結果

熱部署配置(會重啟)

工欲善其事,必先利其器。在開發的時候,難免會反覆進行修改除錯,就目前而言,修改了程式碼後是無法直接編譯生效,所以需要我們新增以下依賴,新增後一定要確保已經依賴噢

  1. 新增如下依賴
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<optional>true</optional>
</dependency>

2.plugin中加入如下

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

                <!--加入部分 start-->
				<configuration>
					<fork>true</fork>
				</configuration>
                <!--加入部分 end-->

			</plugin>
		</plugins>
	</build>
  1. 第三步修改IDE
    settings

Registry

設定完成後重啟IDEA即可,本操作在修改程式碼之後只會做到自動啟動服務

總結

會使用SpringBoot之後,老闆再也不用擔心我寫程式碼的速度,總結下來就是簡單、快速、方便!平時如果我們需要搭建一個spring web專案的時候準備依賴包都要很大一部分時間,現在都不用啦。

作者有話說:喜歡的話就請移步Java面試必修網,請自備水,更多幹、幹、乾貨等著你