SpringBoot基礎教程1-1-2 配置文件介紹

1. 概述

SpringBoot極大的簡化了配置,常用配置都可以application.yml或者application.properties文件中設置。

1.1. 特色

介紹項目的同時,推薦相關IntelliJ IDEA快捷鍵,熟能生巧,無需死記硬背。

2. 本節重點

  • SpringBoot常用配置介紹
  • 多環境如何配置
  • 自定義配置文件

2. 工具

  • IntelliJ IDEA,直接官網下載,Ultimate版本,傻瓜式安裝
  • Maven,IntelliJ IDEA自帶無需安裝
  • Springboot ,版本2.0.3.RELEASE
  • Postman,測試工具,下載地址(密碼:sc1e),解壓無需安裝

3. SpringBoot常用配置介紹

點擊resources -> New -> File,或者快捷鍵ALT+Insert,命名application.yml或者application.properties,推薦使用application.yml更加簡潔

SpringBoot基礎教程1-1-2 配置文件介紹

server:port:設置服務端口,server:servlet:context-path:設置服務根路徑

# 服務相關配置server: # 服務端口配置 port: 8080 # 服務根路徑配置 servlet: context-path: /dev

啟動服務,快捷鍵Shift+F10

SpringBoot基礎教程1-1-2 配置文件介紹

debug:開啟debug模式,開啟後可以看到服務啟動詳細過程,SpringBoot加載了哪些配置和class,適合新手瞭解SpringBoot內部機制

# 開啟debug模式debug: true
SpringBoot基礎教程1-1-2 配置文件介紹

4. 多環境如何配置

一般開發過程會分多套環境,簡單來說,開發環境一套配置,生產環境一套配置,不同環境配置不同,如何處理?

點擊resources -> New -> File,新建配置文件application-dev.yml

# 服務相關配置server: # 服務端口配置 port: 8888 # 服務根路徑配置 servlet: context-path: /dev# 開啟debug模式debug: true

點擊resources -> New -> File,新建配置文件application-pro.yml

# 服務相關配置server: # 服務端口配置 port: 8080 # 服務根路徑配置 servlet: context-path: /# 開啟debug模式debug: false

修改application.yml,配置激活配置

## 多環境配置,激活哪套配置spring: profiles: active: dev

啟動服務,快捷鍵Shift+F10

SpringBoot基礎教程1-1-2 配置文件介紹

測試

SpringBoot基礎教程1-1-2 配置文件介紹

spring:profiles:active: pro 生產環境配置,請自己動手體驗,看看是否生效,切記:無它,熟能生巧

5. 如何解析自定義配置文件(properties文件)

SpringBoot解析配置生成元數據,建議添加依賴

org.springframework.bootspring-boot-configuration-processortrue

點擊resources -> New -> File,新建配置文件user.properties,寫下如下內容

company.user.name=Mkeepercompany.user.age=28

新建UserProperties.java用來保存user.properties中的內容,方便通過對象訪問

@Configuration//指定配置文件,如果不指定,默認解析“application.yml”@PropertySource("classpath:user.properties")//前綴@ConfigurationProperties(prefix = "company.user")public class UserProperties { private String name; private Integer age; // 省略 get set @Override public String toString() { return "UserProperties {" + "name='" + name + '\'' + ", age=" + age + '}'; }}

如果刪除@PropertySource("classpath:user.properties"),SpringBoot將默認解析application.yml中的配置

新建UserController.java,注入UserProperties

@RestControllerpublic class UserController { private static final Logger log = LoggerFactory.getLogger(UserController.class); @Autowired private UserProperties userProperties; @GetMapping("/user") public String user() { log.info("info:"); return userProperties.toString(); }}

快捷鍵Ctrl+E可以快速查看最近閱讀過的文件

測試

SpringBoot基礎教程1-1-2 配置文件介紹

6. 工程目錄

SpringBoot基礎教程1-1-2 配置文件介紹

7. 結束語

無他,熟能生巧,與大家共勉,有任何建議,歡迎留言探討,本文源碼(GitHub:Mkeeper)。


分享到:


相關文章: