天天看點

Spring Boot 學習01-----搭建一個簡單的spring-boot-demo

今天開始要系統性的學習Spring Boot。這個熟悉又陌生的架構,已經陪伴了我2年多。百尺竿頭更進一步,這裡使用Idea來搭建一個SpringBoot項目。

系統環境

工具 版本号
spring-boot 2.4.5
jdk 1.8

實施步驟

  1. 選中 File---->New—>Module,進入建立項目的頁面。
    Spring Boot 學習01-----搭建一個簡單的spring-boot-demo
  2. 進入Module頁面之後,選中Spring Initializer 會引導我們建立一個SpringBoot項目,預設選擇最新的SpringBoot,當然也可以選中Custom,選擇一個我們自己的私域連接配接,不過要確定這連結是有效的。
    Spring Boot 學習01-----搭建一個簡單的spring-boot-demo
  3. 對項目進行配置,指定項目的 groupId和artifactId,這兩個非常關鍵,直接決定了項目名,下面還有可以選在JDK的版本,以及指定包路徑。
    Spring Boot 學習01-----搭建一個簡單的spring-boot-demo
  4. 我們一般都是用SpringBoot來建立一個Web項目,是以需要選中Spring Web
    Spring Boot 學習01-----搭建一個簡單的spring-boot-demo
    點選确認之後,項目就建立成功了,項目的結構如下圖所示:
    Spring Boot 學習01-----搭建一個簡單的spring-boot-demo
    選中啟動類SpringBootDemoNewApplication,右鍵運作項目可以直接可以啟動成功,預設的啟動端口是8080, 預設項目名是/
    Spring Boot 學習01-----搭建一個簡單的spring-boot-demo

不過這樣的啟動是空洞無味了,讓我們給他上點色吧,比如添加一個controller

controller

依賴添加好之後,就是編寫一個簡單的controller了。

package com.jay.spring.boot.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class SampleController {
    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }
}      

說明

預設的通路位址是:http://localhost:8080/

當然我們也可以在classpath下的application.properties中進行修改啟動端口号,比如下面将端口号改成了 9191。

#application.properties
server.port=9191
server.address=127.0.0.1
server.servlet.context-path=/spring-boot-demo-new      

上面, server.servlet.context-path=/spring-boot-demo-new就是設定項目路徑的,現在需要 http://localhost:9191/spring-boot-demo-new/ 才能通路。

至此,一個最簡單的spring-boot的demo就完成了。

啟動項目

前面是通過Idea直接運作啟動類的,當然,也有其他的啟動方式,比如:通過mvn spring-boot:run來啟動項目。這是因為

我們使用了spring-boot-starter-parent POM。

啟動之後就可以通路了,位址為:http://localhost:9191/spring-boot-demo-new/

打包

通過指令mvn package 用來打包。

注意,Spring Boot的這種打包方式需要使用Spring Boot 提供的spring-boot-maven-plugin

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

打包之後,我們可以在target下看到編譯後的class檔案,以及生成的jar,預設的名稱是spring-boot-demo-new-0.0.1-SNAPSHOT.jar

Spring Boot 學習01-----搭建一個簡單的spring-boot-demo

正常執行

正常執行的jar 執行java -jar target/spring-boot-demo-new.jar

啟動後的結果是,啟動端口已經改成 9191,項目名已經改成了 /spring-boot-demo-new

Spring Boot 學習01-----搭建一個簡單的spring-boot-demo

附錄

相關源碼 : https://github.com/XWxiaowei/spring-boot-demo

總結

本文簡單的介紹了如何搭建一個SpringBoot項目,實際上,用Idea來搭建的話還是非常簡單的。

引用