Spring Boot 配置文件深度解析
本文深入探討了 Spring Boot 配置文件的核心作用及其主流格式。通過對比 Properties 與 YAML (YML) 的語法差異、優(yōu)先級及適用場景,結(jié)合 @Value 與 @ConfigurationProperties 注解的代碼實(shí)戰(zhàn),幫助開發(fā)者掌握配置讀取的高級技巧。文章最后通過一個“圖形驗證碼”綜合案例,演示了如何將配置項優(yōu)雅地集成到實(shí)際業(yè)務(wù)中。
1. 配置文件概述:告別硬編碼
在軟件開發(fā)中,硬編碼 (Hard Coding) 是指將數(shù)據(jù)直接嵌入源代碼的行為 。這種做法會導(dǎo)致程序靈活性差,例如手機(jī)字體大小若被寫死,將無法滿足不同用戶的偏好 。
配置文件的作用在于解決硬編碼問題,將易變信息(如數(shù)據(jù)庫連接、端口號、第三方密鑰)集中管理 。當(dāng)程序啟動時,它會從配置文件中讀取數(shù)據(jù)并加載運(yùn)行,從而實(shí)現(xiàn)用戶與應(yīng)用的交互 。
2. Spring Boot 配置文件的三大格式
Spring Boot 在啟動時會自動從 classpath 路徑尋找并加載以下格式的文件 :
| 格式名稱 | 后綴名 | 特點(diǎn) |
|---|---|---|
| Properties | .properties | 早期默認(rèn)格式,創(chuàng)建項目時的默認(rèn)選擇 |
| YAML | .yml | 縮寫形式,開發(fā)中最常用,支持樹形結(jié)構(gòu) |
| YAML | .yaml | 全稱形式,與 .yml 使用方式一致 |
2.1 優(yōu)先級與共存說明
- 共存性:理論上兩者可并存于同一項目 。
- 優(yōu)先級:當(dāng)配置沖突時,
.properties的優(yōu)先級高于.yml。 - 建議:實(shí)際開發(fā)中應(yīng)統(tǒng)一使用一種格式以降低維護(hù)成本 。
3. Properties 語法與讀取實(shí)戰(zhàn)
3.1 基礎(chǔ)語法
Properties 采用 key=value 的鍵值對形式,使用 # 作為注釋 。
文件配置如下:
# 設(shè)置項目啟動端口 server.port=8080 # 數(shù)據(jù)庫連接配置 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb spring.datasource.username=root
3.2 使用 @Value 讀取配置
在 Java 代碼中,可以使用 ${} ({}里面填寫鍵名)格式配合 @Value 注解主動讀取內(nèi)容 。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/prop")
@RestController
public class PropertiesController {
@Value("${spring.datasource.url}")
private String url;
@RequestMapping("/read")
public String readProperties() {
return "從配置文件中讀取url" + url;
}
}運(yùn)行效果:

3.3 properties缺點(diǎn)
properties配置是以key-value的形式配置的,如下圖所示:

從上述配置key看出,properties配置文件中會有很多的冗余的信息,比如這些:

想要解決這個問題,就得使用yml配置文件的格式化了
4. YAML (YML) 進(jìn)階指南
YAML 是一種樹形結(jié)構(gòu)的標(biāo)記語言,通過縮進(jìn)表示層級 。
4.1 核心語法規(guī)范

- 冒號空格:
key和value之間必須有 英文冒號+空格,空格不可省略 。 - 數(shù)據(jù)類型支持:支持字符串、布爾值、整數(shù)、浮點(diǎn)數(shù)以及
null(用~表示) 。
單層級與多層級的表示規(guī)則

多層級的key前面要空兩個格,且同級需對齊!
4.2 yaml語法與讀取示例
yaml文件配置如下

Java代碼讀取配置信息
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/yaml")
@RestController
public class yamlController {
@Value("${yaml}")
private String yaml;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@RequestMapping("/read")
public String read() {
System.out.println(yaml);
System.out.println(username);
System.out.println(password);
return "success";
}
}運(yùn)行結(jié)果

打印配置

4.3 字符串的引號差異
YAML 中字符串默認(rèn)不加引號,但單雙引號有本質(zhì)區(qū)別 :
- 單引號 (‘’):會轉(zhuǎn)義特殊字符,使其變?yōu)槠胀ㄗ址ㄈ?
\n輸出為字符\n) - 雙引號 (“”):不會轉(zhuǎn)義特殊字符,保留其本身含義(如
\n輸出為換行)


4.4 對象、集合與 Map 的讀取
配置對象
YML 配置示例:
student: id: 1 name: Java age: 18
Java 實(shí)體類映射:
對于復(fù)雜數(shù)據(jù)形態(tài),建議使用 @ConfigurationProperties 注解 。
@Data
@ConfigurationProperties(prefix = "student") // 會從配置文件中找到student的前綴
@Configuration
public class Student {
private Integer id;
private String name;
private Integer age;
}運(yùn)行打印結(jié)果

配置集合
YML 配置示例:
dbtypes:
name:
- mysql
- sqlserver
- db2
map:
k1: kk1
k2: kk2
k3: kk3Java 實(shí)體類映射:
對于復(fù)雜數(shù)據(jù)形態(tài),建議使用 @ConfigurationProperties 注解 。
@Data
@ConfigurationProperties(prefix = "dbtypes")
@Configuration
public class DbTypeConfig {
private List<String> name;
private Map<String, String> map;
}
運(yùn)行打印結(jié)果

5. 綜合性練習(xí):驗證碼案例實(shí)戰(zhàn)

本案例基于 Hutool 第三方工具包實(shí)現(xiàn)一個后端生成、校驗驗證碼的功能 。


5.1 需求分析
- 后端生成驗證碼圖片并返回流 。
- 將驗證碼及其生成時間存入
Session。 - 用戶提交驗證碼,后端校驗一致性及有效期(1分鐘內(nèi)有效) 。
5.2 約定前后端交互接口
接口定義
- 生成驗證碼
請求URL:/captcha/getCaptcha響應(yīng):驗證碼圖片內(nèi)容 - 校驗驗證碼是否正確
請求:/captcha/check請求URL: /captcha/check 請求參數(shù): captcha=xn8d
響應(yīng):true
根據(jù)用戶輸?的驗證碼,校驗驗證碼是否正確.true:驗證成功.false:驗證失敗.
配置文件定義(解決硬編碼問題)
在 application.yml 中定義驗證碼的尺寸及 Session 的 Key :
spring:
application:
name: spring-captcha-demo
captcha:
width: 100
height: 40
# 通過設(shè)置session配置項,避免日后需要到處修改
session:
code: SESSION_CODE_KEY
date: SESSION_DATE_KEY驗證碼相關(guān)接口
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.overthinker.spring.captcha.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
@Autowired
private CaptchaProperties captchaProperties;
private static long VILD_MiLLTS_TIME = 5 * 60 * 1000;
@RequestMapping("/getCaptcha")
public void genCaptcha(HttpServletRequest request, HttpServletResponse response) {
//定義圖形驗證碼的長和寬
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
String code = lineCaptcha.getCode();
System.out.println(code);
//圖形驗證碼寫出,可以寫出到文件,也可以寫出到流
try {
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
lineCaptcha.write(response.getOutputStream());
//拿到這個請求的session,并且將code寫入到session
HttpSession session = request.getSession();
session.setAttribute(captchaProperties.getSession().getCode(), code);
//記錄時間保持五分鐘內(nèi)有效
session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
response.getOutputStream().close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@RequestMapping("/check")
public Boolean checkCaptcha(String captcha, HttpSession session) {
//先判斷是否為空
if(!StringUtils.hasLength(captcha)) {
return false;
}
// 從session中獲取code和時間
String code = session.getAttribute(captchaProperties.getSession().getCode()).toString();
long data = (long)session.getAttribute(captchaProperties.getSession().getDate());
if(captcha.equalsIgnoreCase(code) && (System.currentTimeMillis() - data < VILD_MiLLTS_TIME)) {
return true;
}
return false;
}
}前端相關(guān)代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>驗證碼</title>
<style>
#inputCaptcha {
height: 30px;
vertical-align: middle;
}
#verificationCodeImg{
vertical-align: middle;
}
#checkCaptcha{
height: 40px;
width: 100px;
}
</style>
</head>
<body>
<h1>輸入驗證碼</h1>
<div id="confirm">
<input type="text" name="inputCaptcha" id="inputCaptcha">
<img id="verificationCodeImg" src="/captcha/getCaptcha" style="cursor: pointer;" title="看不清?換一張" />
<input type="button" value="提交" id="checkCaptcha">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$("#verificationCodeImg").click(function(){
$(this).hide().attr('src', '/captcha/getCaptcha?dt=' + new Date().getTime()).fadeIn();
});
$("#checkCaptcha").click(function () {
// alert("驗證碼校驗");
$.ajax({
url:'/captcha/check',
type:'post',
data:{
captcha:$('#inputCaptcha').val()
},
success:function (result) {
if(result){
location.href = 'success.html';
}else {
alert("驗證碼錯誤!");
}
}
});
});
</script>
</body>
</html>運(yùn)行結(jié)果


6. 總結(jié)
- Properties 語法簡單但存在冗余,適用于簡單項目 。
- YAML 結(jié)構(gòu)清晰、支持類型豐富,是目前 Spring Boot 開發(fā)的主流選擇 。
- 讀取技巧:簡單配置用
@Value,結(jié)構(gòu)化配置(對象/集合)首選@ConfigurationProperties。 - 建議:yml可以和properties共存,但?個項目中建議只使用?種配置類型文件
參考鏈接:
到此這篇關(guān)于Spring Boot 配置文件深度解析的文章就介紹到這了,更多相關(guān)Spring Boot 配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Springboot配置文件Nacos和環(huán)境變量優(yōu)先級詳解
- SpringBoot中配置文件敏感信息加密解密的實(shí)現(xiàn)方案詳解
- SpringBoot的pom.xml文件中設(shè)置多環(huán)境配置信息方法詳解
- SpringBoot中配置文件pom.xml的使用詳解
- Spring Boot application.yml配置文件示例詳解
- 部署springboot打包不打包配置文件,配置文件為外部配置文件使用詳解
- SpringBoot讀取Nacos上配置文件的步驟詳解
- 詳解SpringBoot依賴注入和使用配置文件
- SpringBoot中的配置文件加載優(yōu)先級詳解
- SpringBoot中使用configtree讀取樹形文件目錄中的配置詳解
相關(guān)文章
Java中實(shí)現(xiàn)WebSocket方法詳解
這篇文章主要介紹了Java中實(shí)現(xiàn)WebSocket方法詳解,WebSocket?是一種新型的網(wǎng)絡(luò)協(xié)議,它允許客戶端和服務(wù)器之間進(jìn)行雙向通信,可以實(shí)現(xiàn)實(shí)時數(shù)據(jù)交互,需要的朋友可以參考下2023-07-07
Java使用路徑通配符加載Resource與profiles配置使用詳解
這篇文章主要介紹了Java使用路徑通配符加載Resource與profiles配置使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
WebSocket獲取httpSession空指針異常的解決辦法
這篇文章主要介紹了在使用WebSocket實(shí)現(xiàn)p2p或一對多聊天功能時,如何獲取HttpSession來獲取用戶信息,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2025-01-01
Spring?cloud網(wǎng)關(guān)gateway進(jìn)行websocket路由轉(zhuǎn)發(fā)規(guī)則配置過程
這篇文章主要介紹了Spring?cloud網(wǎng)關(guān)gateway進(jìn)行websocket路由轉(zhuǎn)發(fā)規(guī)則配置過程,文中還通過實(shí)例代碼介紹了Spring?Cloud?Gateway--配置路由的方法,需要的朋友可以參考下2023-04-04
SpringBoot整合EasyCaptcha實(shí)現(xiàn)圖形驗證碼功能
這篇文章主要介紹了SpringBoot整合EasyCaptcha實(shí)現(xiàn)圖形驗證碼功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-02-02

