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

