最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java從配置文件中獲取參數(shù)的三種常見場景和完整示例

 更新時間:2026年01月09日 10:00:54   作者:hellotutu  
在 Java 中從配置文件獲取參數(shù)是開發(fā)中的常見需求,不同配置文件格式和框架有不同的實現(xiàn)方式,以下是 最常用的 3 種場景+完整示例,覆蓋原生 Java 和 Spring Boot 項目,直接復用即可,需要的朋友可以參考下

引言

在 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(綁定配置類,推薦多配置項)

適合配置項較多的場景,將配置綁定到一個實體類,結構更清晰(推薦):

  1. 配置文件(同 application.properties);
  2. 配置類:
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;
    }
}
  1. 使用配置類:
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.propertiesapplication-dev.properties(開發(fā)環(huán)境)等,通過 spring.profiles.active=dev 切換環(huán)境。
  • 類型轉換:Spring 自動將配置值轉換為 intboolean 等類型,無需手動處理。
  • @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;
    }
}

四、常見問題排查

  1. 配置文件找不到:確保配置文件在 src/main/resources 目錄下(Maven 項目默認資源目錄),打包后檢查 Jar 包中是否包含該文件。
  2. @Value 注入為 null:確保類被 Spring 管理(添加 @Component 等注解),且配置項 key 與注解中一致(區(qū)分大小寫)。
  3. yaml 格式錯誤:yaml 對縮進敏感(必須用空格,不能用 Tab),層級縮進要一致,否則配置無法解析。
  4. 類型轉換失敗:確保配置值與目標類型匹配(如 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ū)別【推薦】

    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)計的示例代碼

    本文主要介紹了SpringBoot整合Redis實現(xiàn)訪問量統(tǒng)計的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • spring boot啟動加載數(shù)據(jù)原理分析

    spring boot啟動加載數(shù)據(jù)原理分析

    實際應用中,我們會有在項目服務啟動的時候就去加載一些數(shù)據(jù)或做一些事情這樣的需求。這時spring Boot 為我們提供了一個方法,通過實現(xiàn)接口 CommandLineRunner 來實現(xiàn)。下面給大家詳細介紹下,需要的的朋友參考下吧
    2017-04-04
  • MyBatis批量操作XML的完整實現(xiàn)方案

    MyBatis批量操作XML的完整實現(xiàn)方案

    本文介紹了MyBatis通過XML映射文件實現(xiàn)批量插入、更新和刪除的完整方案,包括單條SQL批量插入、批量插入并返回主鍵、批量更新、批量刪除以及動態(tài)批量操作,最后,分享了最佳實踐建議,需要的朋友可以參考下
    2025-12-12
  • Spring?零基礎入門WebFlux框架體系

    Spring?零基礎入門WebFlux框架體系

    Spring5發(fā)布有兩年了,隨Spring5一起發(fā)布了一個和Spring?WebMvc同級的Spring?WebFlux。這是一個支持反應式編程模型的新框架體系。反應式模型區(qū)別于傳統(tǒng)的MVC最大的不同是異步的、事件驅動的、非阻塞的,這使得應用程序的并發(fā)性能會大大提高,單位時間能夠處理更多的請求
    2022-07-07
  • springboot+thymeleaf+layui的實現(xiàn)示例

    springboot+thymeleaf+layui的實現(xiàn)示例

    本文主要介紹了springboot+thymeleaf+layui的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-12-12
  • Java優(yōu)秀類庫Hutool使用示例

    Java優(yōu)秀類庫Hutool使用示例

    Hutool是一個小而全的Java工具類庫,通過靜態(tài)方法封裝,降低相關API的學習成本,提高工作效率,涵蓋了Java開發(fā)開發(fā)中的方方面面,使用Hutool可節(jié)省開發(fā)人員對項目中公用類和公用工具方法的封裝時間,使開發(fā)專注于業(yè)務,同時可以最大限度的避免封裝不完善帶來的bug
    2023-02-02
  • Maven與Gradle的區(qū)別對比分析

    Maven與Gradle的區(qū)別對比分析

    這篇文章給大家給大家介紹了Maven與Gradle的區(qū)別對比分析,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2026-05-05
  • java list與數(shù)組之間的轉換詳細解析

    java list與數(shù)組之間的轉換詳細解析

    以下是對java中l(wèi)ist與數(shù)組之間的轉換進行了詳細的分析介紹,需要的朋友可以過來參考下
    2013-09-09
  • IDEA反編譯jar,查看源碼方式

    IDEA反編譯jar,查看源碼方式

    該篇文章總結了查看Java本地jar包注釋的幾種方法,包括使用快捷鍵CTRL+q和在設置中設置自動浮現(xiàn)注釋
    2024-11-11

最新評論

双牌县| 仙桃市| 泽库县| 本溪市| 明水县| 伊春市| 砀山县| 林甸县| 克东县| 鸡泽县| 乌什县| 博罗县| 新邵县| 根河市| 瑞昌市| 寻甸| 会东县| 东阳市| 济源市| 南靖县| 咸阳市| 兰考县| 察隅县| 元阳县| 瑞昌市| 忻城县| 留坝县| 东明县| 泰和县| 西林县| 清河县| 河曲县| 家居| 抚宁县| 阜城县| 南丰县| 凉山| 巴东县| 大厂| 辛集市| 黄陵县|