一、idea創建spring boot項目
點擊展開查看-IDEA創建spring boot項目
二、spring boot配置文件
先改一下 spring boot配置文件的后綴從application.properties 改成application.yml
1、設置spring boot端口
server:
port: 10086
2、設置spring boot隨機端口
我們訪問某個微服務的時候,可以從注冊中心獲取到對應的IP及端口號
所以動態擴容的時候,可以使用隨機端口啟動項目
server:
port: ${random.int(10000,65535)} #隨機端口
3、設置服務根路徑(servlet.context-path)
現在有一個hello接口代碼如下:
@RestController
@RequestMapping("/test")
public class TestCollection {
@RequestMapping("hello")
public String getValue(){
return "hello world";
}
}
如果配置端口是:10086
如果根路徑配置如下:要訪問hello接口,請求地址就是:http://127.0.0.1:10086/test/hello
servlet:
context-path: / #設置服務的根路徑
如果根路徑配置如下:要訪問hello接口,請求地址就是:http://127.0.0.1:10086/hello_world/test/hello
servlet:
context-path: /hello_world #設置服務的根路徑
4、Spring Boot 更換 Banner
只需要在src/main/resources路徑下新建一個banner.txt文件,banner.txt中填寫好需要打印的字符串內容即可。
banner.txt的內容可以訪問這個網站【 https://www.bootschool.net/ascii-art 】然后粘貼到banner.txt
下面是程序員常用的banner.txt內容可以直接使用:
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕機 永無BUG //
////////////////////////////////////////////////////////////////////
0000000 0000000 000000 000 0000000000 000 000
000 000 000 00 000 000 000 000 000 000 000
00 000 000 00 000 000 000 000 000 000
00 000 000 000 00 0000 000 000 000 000
000 0000 000 0000 0000 000 000 000 000 000
000000 000 00000 00 000 000 000 000 000 000
00 000 00 000 000 000 00 000 000
000 000 00 00 00 00 000 000 0000 0000 000 000
0000000 00000000 00000000 000 000 0000000000 0000000000
三、spring boot多環境配置,按照spring.profiles.active來讀取不同的配置文件
我們在yml的配置文件中,使用spring.profiles.active來讀取不同的配置環境
項目啟動時,日志會輸出【The following profiles are active: dev】:
2021-07-25 23:12:55.325 INFO 28167 --- [ restartedMain] c.e.s.SpringbootHelloWorldApplication : The following profiles are active: dev
當我把這個項目mvn install 后打成 hello.jar,通過java命令啟動項目,可以在啟動的時候讀取不同環境的配置文件,命令如下:
1、命令一(親測有效~):
java -jar hello.jar --spring.profiles.active=prod
下面是效果截圖:
2、命令二(親測無效~):
java -jar hello.jar --Dspring.profiles.active=prod
第二個是多了個大寫的D --Dxxx=xxx
java程序啟動參數-D含義詳解
-D<名稱>=<值> : set a system property 設置系統屬性。
我看網上不少文章都是帶大寫的D的,估計是以前的spring boot版本支持吧
下圖命令二 輸出的結果,看的出來配置沒生效