Java從配置文件中獲取參數(shù)的三種常見場景和完整示例
引言
在 Java 中從配置文件獲取參數(shù)是開發(fā)中的常見需求,不同配置文件格式(properties、yaml)和框架(原生 Java、Spring Boot)有不同的實(shí)現(xiàn)方式。以下是 最常用的 3 種場景+完整示例,覆蓋原生 Java 和 Spring Boot 項(xiàng)目,直接復(fù)用即可。
一、場景 1:原生 Java + properties 配置文件(無框架)
properties 是 Java 原生支持的配置文件格式,無需額外依賴,適合簡單項(xiàng)目(如純 Java 工具類、非 Spring 項(xiàng)目)。
1. 配置文件準(zhǔn)備
在項(xiàng)目 src/main/resources 目錄下創(chuàng)建 config.properties 文件:
# 數(shù)據(jù)庫配置 db.url=jdbc:mysql://localhost:3306/test db.username=root db.password=123456 # 應(yīng)用配置 app.name=JavaConfigDemo app.port=8080 app.upload.path=D:/upload/images
2. 代碼實(shí)現(xiàn)(原生 Properties 類)
通過 java.util.Properties 類讀取配置文件,核心是加載文件流并解析鍵值對:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesConfigReader {
// 靜態(tài) Properties 對象,全局復(fù)用
private static final Properties properties = new Properties();
// 靜態(tài)代碼塊:初始化時加載配置文件
static {
try {
// 加載 resources 目錄下的 config.properties
InputStream inputStream = PropertiesConfigReader.class
.getClassLoader()
.getResourceAsStream("config.properties");
if (inputStream == null) {
throw new RuntimeException("配置文件 config.properties 未找到");
}
// 加載配置到 Properties 對象
properties.load(inputStream);
inputStream.close(); // 關(guān)閉流
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("加載配置文件失敗:" + e.getMessage());
}
}
/**
* 根據(jù) key 獲取配置值(字符串類型)
*/
public static String getString(String key) {
return properties.getProperty(key);
}
/**
* 根據(jù) key 獲取配置值(整數(shù)類型,默認(rèn)值重載)
*/
public static int getInt(String key, int defaultValue) {
String value = properties.getProperty(key);
return value == null ? defaultValue : Integer.parseInt(value);
}
/**
* 根據(jù) key 獲取配置值(整數(shù)類型,無默認(rèn)值則拋異常)
*/
public static int getInt(String key) {
String value = properties.getProperty(key);
if (value == null) {
throw new IllegalArgumentException("配置項(xiàng) " + key + " 不存在");
}
return Integer.parseInt(value);
}
// 測試
public static void main(String[] args) {
// 獲取字符串配置
String dbUrl = getString("db.url");
String uploadPath = getString("app.upload.path");
System.out.println("數(shù)據(jù)庫URL:" + dbUrl);
System.out.println("上傳路徑:" + uploadPath);
// 獲取整數(shù)配置
int appPort = getInt("app.port");
int timeout = getInt("app.timeout", 3000); // 不存在時使用默認(rèn)值 3000
System.out.println("應(yīng)用端口:" + appPort);
System.out.println("超時時間:" + timeout);
}
}
3. 核心說明
- 配置文件路徑:
src/main/resources是類路徑(classpath)默認(rèn)目錄,文件會被打包到 Jar 中,通過ClassLoader.getResourceAsStream()加載。 - 類型轉(zhuǎn)換:原生
Properties只支持字符串,需手動轉(zhuǎn)換為int、boolean等類型(可封裝工具方法簡化)。 - 靜態(tài)代碼塊:確保配置文件只加載一次,避免重復(fù) IO 操作。
二、場景 2:Spring Boot + application.properties(最常用)
Spring Boot 項(xiàng)目默認(rèn)支持 application.properties 配置文件,通過 @Value 注解或 Environment 接口可快速獲取參數(shù),無需手動加載文件。
1. 配置文件準(zhǔn)備
在 src/main/resources 目錄下創(chuàng)建 application.properties(Spring Boot 默認(rèn)配置文件):
# 服務(wù)器配置 server.port=8080 # 數(shù)據(jù)庫配置 spring.datasource.url=jdbc:mysql://localhost:3306/springdemo spring.datasource.username=root spring.datasource.password=123456 # 自定義配置 app.upload.path=D:/spring-upload app.max.file.size=5MB app.debug=true
2. 代碼實(shí)現(xiàn)(3 種方式)
方式 1:@Value 注解(直接注入,最簡單)
適合在 Bean 中直接注入單個配置項(xiàng):
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component // 必須是 Spring 管理的 Bean(@Component/@Service/@Controller 等)
public class AppConfig {
// 注入字符串類型配置
@Value("${app.upload.path}")
private String uploadPath;
// 注入整數(shù)類型(Spring 自動轉(zhuǎn)換)
@Value("${server.port}")
private int serverPort;
// 注入布爾類型
@Value("${app.debug}")
private boolean debug;
// 注入時指定默認(rèn)值(配置不存在時使用)
@Value("${app.default.value:default-str}")
private String defaultValue;
// Getter 方法(供其他類調(diào)用)
public String getUploadPath() {
return uploadPath;
}
public int getServerPort() {
return serverPort;
}
public boolean isDebug() {
return debug;
}
public String getDefaultValue() {
return defaultValue;
}
}
方式 2:Environment 接口(動態(tài)獲取,適合多環(huán)境)
適合在代碼中動態(tài)獲取配置(如根據(jù)條件切換配置項(xiàng)):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
@Service
public class ConfigService {
// 注入 Environment 對象
@Autowired
private Environment env;
public void getConfig() {
// 獲取字符串配置
String dbUrl = env.getProperty("spring.datasource.url");
// 獲取整數(shù)配置(指定默認(rèn)值)
int maxSize = env.getProperty("app.max.file.size", Integer.class, 10);
// 獲取布爾配置
boolean debug = env.getProperty("app.debug", Boolean.class, false);
System.out.println("數(shù)據(jù)庫URL:" + dbUrl);
System.out.println("最大文件大?。? + maxSize);
System.out.println("調(diào)試模式:" + debug);
}
}
方式 3:@ConfigurationProperties(綁定配置類,推薦多配置項(xiàng))
適合配置項(xiàng)較多的場景,將配置綁定到一個實(shí)體類,結(jié)構(gòu)更清晰(推薦):
- 配置文件(同
application.properties); - 配置類:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
// prefix = "app" 表示綁定配置文件中以 "app." 開頭的配置項(xiàng)
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String uploadPath; // 對應(yīng) app.upload.path
private int maxFileSize; // 對應(yīng) app.max.file.size(自動轉(zhuǎn)換下劃線/短橫線)
private boolean debug; // 對應(yīng) app.debug
// 必須提供 Setter 方法(Spring 會通過 Setter 注入值)
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
}
public void setMaxFileSize(int maxFileSize) {
this.maxFileSize = maxFileSize;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
// Getter 方法
public String getUploadPath() {
return uploadPath;
}
public int getMaxFileSize() {
return maxFileSize;
}
public boolean isDebug() {
return debug;
}
}
- 使用配置類:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigController {
@Autowired
private AppProperties appProperties;
@GetMapping("/config")
public String getConfig() {
return "上傳路徑:" + appProperties.getUploadPath() +
",最大文件大小:" + appProperties.getMaxFileSize() +
",調(diào)試模式:" + appProperties.isDebug();
}
}
3. 核心說明
- 配置文件優(yōu)先級:Spring Boot 會加載
application.properties、application-dev.properties(開發(fā)環(huán)境)等,通過spring.profiles.active=dev切換環(huán)境。 - 類型轉(zhuǎn)換:Spring 自動將配置值轉(zhuǎn)換為
int、boolean等類型,無需手動處理。 @ConfigurationProperties優(yōu)勢:支持配置校驗(yàn)(如@NotNull、@Min)、自動綁定下劃線/短橫線命名(如app.max-file-size對應(yīng)maxFileSize)。
三、場景 3:Spring Boot + application.yml(更簡潔)
yaml 格式比 properties 更簡潔,支持層級結(jié)構(gòu),Spring Boot 同樣原生支持。
1. 配置文件準(zhǔn)備
在 src/main/resources 目錄下創(chuàng)建 application.yml:
# 服務(wù)器配置
server:
port: 8080
# 數(shù)據(jù)庫配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/springdemo
username: root
password: 123456
# 自定義配置(層級結(jié)構(gòu))
app:
upload:
path: D:/spring-upload
max:
file:
size: 5
debug: true
timeout: 3000
2. 代碼實(shí)現(xiàn)(與 properties 完全兼容)
yaml 只是配置文件格式不同,Java 代碼獲取方式與 Spring Boot + properties 完全一致,無需修改:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
// 方式 1:@Value 注解
@Component
public class YamlConfig {
@Value("${app.upload.path}") // 對應(yīng) app.upload.path
private String uploadPath;
@Value("${app.max.file.size}") // 對應(yīng) app.max.file.size
private int maxFileSize;
// Getter 方法
public String getUploadPath() {
return uploadPath;
}
public int getMaxFileSize() {
return maxFileSize;
}
}
// 方式 2:@ConfigurationProperties(推薦)
@Component
@ConfigurationProperties(prefix = "app")
public class AppYamlProperties {
private Upload upload; // 對應(yīng) app.upload 層級
private Max max; // 對應(yīng) app.max 層級
private boolean debug;
private int timeout;
// 內(nèi)部靜態(tài)類(對應(yīng)層級配置)
public static class Upload {
private String path; // 對應(yīng) app.upload.path
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
public static class Max {
private File file; // 對應(yīng) app.max.file
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public static class File {
private int size; // 對應(yīng) app.max.file.size
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
}
// Getter + Setter 方法
public Upload getUpload() {
return upload;
}
public void setUpload(Upload upload) {
this.upload = upload;
}
public Max getMax() {
return max;
}
public void setMax(Max max) {
this.max = max;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
3. 使用示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YamlConfigController {
@Autowired
private AppYamlProperties appYamlProperties;
@GetMapping("/yaml-config")
public String getYamlConfig() {
String uploadPath = appYamlProperties.getUpload().getPath();
int maxFileSize = appYamlProperties.getMax().getFile().getSize();
boolean debug = appYamlProperties.isDebug();
return "上傳路徑:" + uploadPath +
",最大文件大?。? + maxFileSize +
",調(diào)試模式:" + debug;
}
}
四、常見問題排查
- 配置文件找不到:確保配置文件在
src/main/resources目錄下(Maven 項(xiàng)目默認(rèn)資源目錄),打包后檢查 Jar 包中是否包含該文件。 - @Value 注入為 null:確保類被 Spring 管理(添加
@Component等注解),且配置項(xiàng) key 與注解中一致(區(qū)分大小寫)。 - yaml 格式錯誤:yaml 對縮進(jìn)敏感(必須用空格,不能用 Tab),層級縮進(jìn)要一致,否則配置無法解析。
- 類型轉(zhuǎn)換失敗:確保配置值與目標(biāo)類型匹配(如
app.port配置為字符串"abc"會導(dǎo)致int轉(zhuǎn)換失?。?/li>
五、總結(jié)
| 場景 | 推薦方式 | 優(yōu)勢 |
|---|---|---|
| 原生 Java 項(xiàng)目 | Properties 工具類 | 無依賴、簡單易用 |
| Spring Boot 單配置項(xiàng) | @Value 注解 | 代碼簡潔、快速注入 |
| Spring Boot 多配置項(xiàng) | @ConfigurationProperties + 配置類 | 結(jié)構(gòu)清晰、支持校驗(yàn)、適配層級配置 |
| 偏好簡潔格式 | application.yml + @ConfigurationProperties | 層級分明、配置文件更簡潔 |
根據(jù)項(xiàng)目類型選擇合適的方式,Spring Boot 項(xiàng)目優(yōu)先使用 @ConfigurationProperties(配合 yaml),原生 Java 項(xiàng)目使用 Properties 工具類即可。
以上就是Java從配置文件中獲取參數(shù)的三種常見場景和完整示例的詳細(xì)內(nèi)容,更多關(guān)于Java從配置文件中獲取參數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java編程synchronized與lock的區(qū)別【推薦】
互聯(lián)網(wǎng)信息泛濫環(huán)境下少有的良心之作!如果您想對Java編程synchronized與lock的區(qū)別有所了解,這篇文章絕對值得!分享給大家,供需要的朋友參考。不說了,我先學(xué)習(xí)去了。2017-10-10
SpringBoot整合Redis實(shí)現(xiàn)訪問量統(tǒng)計(jì)的示例代碼
本文主要介紹了SpringBoot整合Redis實(shí)現(xiàn)訪問量統(tǒng)計(jì)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
spring boot啟動加載數(shù)據(jù)原理分析
實(shí)際應(yīng)用中,我們會有在項(xiàng)目服務(wù)啟動的時候就去加載一些數(shù)據(jù)或做一些事情這樣的需求。這時spring Boot 為我們提供了一個方法,通過實(shí)現(xiàn)接口 CommandLineRunner 來實(shí)現(xiàn)。下面給大家詳細(xì)介紹下,需要的的朋友參考下吧2017-04-04
MyBatis批量操作XML的完整實(shí)現(xiàn)方案
本文介紹了MyBatis通過XML映射文件實(shí)現(xiàn)批量插入、更新和刪除的完整方案,包括單條SQL批量插入、批量插入并返回主鍵、批量更新、批量刪除以及動態(tài)批量操作,最后,分享了最佳實(shí)踐建議,需要的朋友可以參考下2025-12-12
springboot+thymeleaf+layui的實(shí)現(xiàn)示例
本文主要介紹了springboot+thymeleaf+layui的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-12-12
java list與數(shù)組之間的轉(zhuǎn)換詳細(xì)解析
以下是對java中l(wèi)ist與數(shù)組之間的轉(zhuǎn)換進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下2013-09-09

