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

1. 概述

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

1.1. 特點

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

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更加簡潔github

1

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

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

啓動服務,快捷鍵Shift+F10windows

2

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

# 開啓debug模式
debug: true

3

4. 多環境如何配置

通常開發過程會分多套環境,簡單來講,開發環境一套配置,生產環境一套配置,不一樣環境配置不一樣,如何處理?ide

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

# 服務相關配置
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

4

測試

5

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

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

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

<!--該依賴只會在編譯時調用-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>

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

company.user.name=Mkeeper
company.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

@RestController
public 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能夠快速查看最近閱讀過的文件

測試

6. 工程目錄

7. 結束語

無他,熟能生巧,與你們共勉,有任何建議,歡迎留言探討,本文源碼


歡迎關注博主公衆號:Java十分鐘

歡迎關注博主公衆號

相關文章
相關標籤/搜索