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

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

引言

SpringBoot是由Pivotal團隊提供的全新框架,從最根本上來說,Spring Boot就是簡化開發人員從0構建項目的繁瑣步驟,巧妙的封裝了不少插件模塊,讓開發人員再也不擔憂版本依賴或複雜的三方依賴問題,它可以被任意項目的構建系統所使用。java

入門項目

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

工具

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

項目快速創建方式一:

首先咱們在SPRING INITIALIZR 上建一個簡單項目,並導入到IDEA中,以下圖:redis

 
詳見網址

 

 
下一步,導入到工程
 
下一步,選擇已有模塊
 
下一步,更改maven變量
 
下一步,選擇JDK1.8目錄
 
簡單項目創建完成
項目快速創建方式二(經常使用):

步驟 File—>New—>Projectspring

 
手動快速創建

 

 
輸入maven信息
 
選擇web,下一步

下一步,而後直接完成,選擇new window便可數據庫

 
建立完成,下面咱們解析剛剛涉及到的幾個點

 

工程結構

DemoApplication.java:應用程序啓動入口,可直接Run啓動服務,相似於tomcat的start.sh
DemoApplicationTests.java:Junit測試類,已自動注入加載了SpringBoot容器的上下文
application.properties:配置屬性空文件,可改成application.yml文件,SpringBoot都能識別
pom.xml:maven工程定義文件,代表該項目的maven座標信息json

疑問解析

  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>

 

此處詳見官方文檔:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-yaml-shortcomings 模塊:13.2.2 Using Spring Boot without the Parent POM

經常使用依賴模塊

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註解等價於@Controller+@ResponseBody的結合,使用這個註解的類裏面的方法都以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面試必修網 https://www.itmsbx.com ,請自備水,更多幹、幹、乾貨等着你

相關文章
相關標籤/搜索