Spring Boot 學習01-----搭建一個簡單的spring-boot-demo
今天開始要系統(tǒng)性的學習Spring Boot。這個熟悉又陌生的框架,已經陪伴了我2年多。百尺竿頭更進一步,這里使用Idea來搭建一個SpringBoot項目。
系統(tǒng)環(huán)境
工具 | 版本號 |
---|---|
spring-boot | 2.4.5 |
jdk | 1.8 |
實施步驟
- 選中 File---->New—>Module,進入創(chuàng)建項目的頁面。
- 進入Module頁面之后,選中Spring Initializer 會引導我們創(chuàng)建一個SpringBoot項目,默認選擇最新的SpringBoot,當然也可以選中Custom,選擇一個我們自己的私域連接,不過要確保這鏈接是有效的。
- 對項目進行配置,指定項目的 groupId和artifactId,這兩個非常關鍵,直接決定了項目名,下面還有可以選在JDK的版本,以及指定包路徑。
- 我們一般都是用SpringBoot來創(chuàng)建一個Web項目,所以需要選中Spring Web
點擊確認之后,項目就創(chuàng)建成功了,項目的結構如下圖所示:
選中啟動類SpringBootDemoNewApplication,右鍵運行項目可以直接可以啟動成功,默認的啟動端口是 8080, 默認項目名是 /
不過這樣的啟動是空洞無味了,讓我們給他上點色吧,比如添加一個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
正常執(zhí)行
正常執(zhí)行的jar 執(zhí)行java -jar target/spring-boot-demo-new.jar
啟動后的結果是,啟動端口已經改成 9191,項目名已經改成了 /spring-boot-demo-new
附錄
相關源碼 : https://github.com/XWxiaowei/spring-boot-demo
總結
本文簡單的介紹了如何搭建一個SpringBoot項目,實際上,用Idea來搭建的話還是非常簡單的。
引用
http://www.cnblogs.com/larryzeal/p/5765945.html
作者:碼農飛哥
微信公眾號:碼農飛哥