1. 程式人生 > >一起來學SpringBoot | 第一篇:構建第一個SpringBoot工程

一起來學SpringBoot | 第一篇:構建第一個SpringBoot工程

文章目錄
1. 設計的目標
2. 前提
3. 建立專案
 3.1. 目錄結果
 3.2. pom.xml 依賴
 3.3. 主函式入口
 3.4. 初窺配置檔案
3.5. 測試
4. 拓展知識
 4.1. 自定義Banner
5. 總結
6. 說點什麼

SpringBoot 是為了簡化 Spring 應用的建立、執行、除錯、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程

未接觸 SpringBoot 之前,搭建一個普通的 WEB 工程往往需要花費30分鐘左右,如果遇到點奇葩的問題耽擱的時間會更長一點,但自從用了SpringBoot 後,真正體會到什麼叫分分鐘搭建一個WEB,讓我擁有更多的時間跟我的小夥伴們嘮嗑了。使用 SpringBoot 後發現一切是如此的簡單(還記得讀書那會被JAR包,xml支配的恐懼嗎,如今都可以說 good bye)

設計的目標

為所有使用 Spring 的開發者提供一個更簡單,快速的入門體驗 提供一些常見的功能、如監控、WEB容器,健康,安全等功能 幹掉XML,遵循規範,開箱即用

前提

SpringBoot 為我們提供了一系列的依賴包,所以需要構建工具的支援:Maven 或 Gradle。由於本人更習慣使用Maven所以後續案例都是基於Maven 與 IntelliJ IDEA,同時這裡是基於最新的SpringBoot2編寫的哦…

建立專案

初次接觸,我們先來看看如何建立一個Spring Boot專案,這裡以IntelliJ IDEA為例,其他的IDE工具小夥伴們自行搜尋建立方式。建立完專案後,各位小夥伴請認真、細心的對比下與傳統的WEB工程有何區別(如:目錄結構)。

點選File -> Project

如果用過 Eclipse/IDEA 等工具的,對建立專案肯定不會陌生,但為了照顧第一次使用的我貼上了圖文 在這裡插入圖片描述

選擇Spring Initializr

到這一步選擇的時候,如圖中選項的是Spring Initializr(官方的構建外掛,需要聯網),第二個是自己選擇Maven構建,為了更好的適合初學者,我們將在本章用外掛構建

填寫專案基本資訊

Group: 組織ID,一般分為多個段,這裡我只說兩段,第一段為域,第二段為公司名稱。域又分為 org、com、cn等等,其中 org為非營利組織,com為商業組織。如阿里、淘寶(com.alibaba/com.taobao) Artifact:

唯一識別符號,一般是專案名稱

選擇包

Spring Initializr 為我們提供了很多的選項,不同的選項有不同的作用,在初期我們只需要依賴Web -> Web 就可以了,選擇好依賴包之後點選Next -> Finish

目錄結果


- src
    -main
        -java
            -package
                #主函式,啟動類,執行它如果運行了 Tomcat、Jetty、Undertow 等容器
                -SpringbootApplication	
        -resouces
            #存放靜態資源 js/css/images 等
            - statics
            #存放 html 模板檔案
            - templates
            #主要的配置檔案,SpringBoot啟動時候會自動載入application.yml/application.properties		
            - application.yml
    #測試檔案存放目錄		
    -test
 # pom.xml 檔案是Maven構建的基礎,裡面包含了我們所依賴JAR和Plugin的資訊
- pom

pom.xml 依賴

因為使用了 Spring Initializr 外掛,所以如下的配置都不需要我們自己去寫啦,需要注意的是版本要選擇 RELEASE ,穩定版本BUG少

<?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.battcn</groupId>
	<artifactId>chapter1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>chapter1</name>
	<description>我的用第一個SpringBoot工程</description>

	<!--版本採用的是最新的 2.0.1.RELEASE TODO 開發中請記得版本一定要選擇 RELEASE 哦 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.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>
		<!-- 預設就內嵌了Tomcat 容器,如需要更換容器也極其簡單-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 測試包,當我們使用 mvn package 的時候該包並不會被打入,因為它的生命週期只在 test 之內-->
		<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>

主函式入口

注意事項: 一個專案中切記不要出現多個 main 函式,否在在打包的時候 spring-boot-maven-plugin 將找不到主函式(主動指定打包主函式入口除外…)

/**
 * 我的第一個SpringBoot程式
 * 其中 @RestController 等同於 (@Controller 與 @ResponseBody)
 *
 * @author Levin
 */
@RestController
@SpringBootApplication
public class Chapter1Application {

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

    @GetMapping("/demo1")
    public String demo1() {
        return "Hello battcn";
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        // 目的是
        return args -> {
            System.out.println("來看看 SpringBoot 預設為我們提供的 Bean:");
            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            Arrays.stream(beanNames).forEach(System.out::println);
        };
    }
}

初窺配置檔案

從啟動日誌中可以發現,SpringBoot 預設的埠是 8080 ,那麼如果埠被佔用了怎麼辦呢?不要慌,問題不大,配置檔案分分鐘解決你的困擾…

2018-04-20 16:14:46.725  INFO 11184 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

修改預設配置

# 預設的 8080 我們將它改成 9090 
server.port=9090
# 未定義上下文路徑之前 地址是 http://localhost:8080 定義了後 http://localhost:9090 你能在tomcat做的事情,配置檔案都可以
server.servlet.context-path=/chapter1

在啟動一次看看日誌

2018-04-20 16:14:46.725  INFO 11184 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

測試

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.junit.Assert.assertEquals;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Chapter1ApplicationTests {


    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        // TODO 因為我們修改了 content-path 所以請求後面要帶上
        this.base = new URL("http://localhost:" + port + "/chapter1/demo1");
    }

    @Test
    public void demo1() throws Exception {
        ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
        assertEquals(response.getBody(), "Hello battcn");
    }
}

拓展知識

自定義Banner SpringBoot 啟動的時候我們可以看到如下內容,這一塊其實是可以自定義的哦,而且在 2.X 版本中,它支援的格式從文字擴充套件到banner.txt、banner.jpg、banner.gif、banner.jpeg 等等,只需要在 resouces 目錄下新增指定命名的檔案即可

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)

總結

目前很多大佬都寫過關於 SpringBoot 的教程了,如有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.1.RELEASE編寫,包括新版本的特性都會一起介紹…

說點什麼

個人QQ:1837307557 battcn開源群(適合新手):391619659 微信公眾號(歡迎調戲):battcn 個人部落格:http://blog.battcn.com/