Java从配置文件中获取参数的三种常见场景和完整示例

 更新时间:2026年01月09日 10:00:54   作者:hellotutu  
在 Java 中从配置文件获取参数是开发中的常见需求,不同配置文件格式和框架有不同的实现方式,以下是 最常用的 3 种场景+完整示例,覆盖原生 Java 和 Spring Boot 项目,直接复用即可,需要的朋友可以参考下

引言

在 Java 中从配置文件获取参数是开发中的常见需求,不同配置文件格式(propertiesyaml)和框架(原生 Java、Spring Boot)有不同的实现方式。以下是 最常用的 3 种场景+完整示例,覆盖原生 Java 和 Spring Boot 项目,直接复用即可。

一、场景 1:原生 Java + properties 配置文件(无框架)

properties 是 Java 原生支持的配置文件格式,无需额外依赖,适合简单项目(如纯 Java 工具类、非 Spring 项目)。

1. 配置文件准备

在项目 src/main/resources 目录下创建 config.properties 文件:

# 数据库配置
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. 代码实现(原生 Properties 类)

通过 java.util.Properties 类读取配置文件,核心是加载文件流并解析键值对:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesConfigReader {
    // 静态 Properties 对象,全局复用
    private static final Properties properties = new Properties();

    // 静态代码块:初始化时加载配置文件
    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());
        }
    }

    /**
     * 根据 key 获取配置值(字符串类型)
     */
    public static String getString(String key) {
        return properties.getProperty(key);
    }

    /**
     * 根据 key 获取配置值(整数类型,默认值重载)
     */
    public static int getInt(String key, int defaultValue) {
        String value = properties.getProperty(key);
        return value == null ? defaultValue : Integer.parseInt(value);
    }

    /**
     * 根据 key 获取配置值(整数类型,无默认值则抛异常)
     */
    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("数据库URL:" + dbUrl);
        System.out.println("上传路径:" + uploadPath);

        // 获取整数配置
        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 只支持字符串,需手动转换为 intboolean 等类型(可封装工具方法简化)。
  • 静态代码块:确保配置文件只加载一次,避免重复 IO 操作。

二、场景 2:Spring Boot + application.properties(最常用)

Spring Boot 项目默认支持 application.properties 配置文件,通过 @Value 注解或 Environment 接口可快速获取参数,无需手动加载文件。

1. 配置文件准备

src/main/resources 目录下创建 application.properties(Spring Boot 默认配置文件):

# 服务器配置
server.port=8080

# 数据库配置
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. 代码实现(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;

    // 注入整数类型(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 接口(动态获取,适合多环境)

适合在代码中动态获取配置(如根据条件切换配置项):

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");
        // 获取整数配置(指定默认值)
        int maxSize = env.getProperty("app.max.file.size", Integer.class, 10);
        // 获取布尔配置
        boolean debug = env.getProperty("app.debug", Boolean.class, false);

        System.out.println("数据库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. 核心说明

  • 配置文件优先级:Spring Boot 会加载 application.propertiesapplication-dev.properties(开发环境)等,通过 spring.profiles.active=dev 切换环境。
  • 类型转换:Spring 自动将配置值转换为 intboolean 等类型,无需手动处理。
  • @ConfigurationProperties 优势:支持配置校验(如 @NotNull@Min)、自动绑定下划线/短横线命名(如 app.max-file-size 对应 maxFileSize)。

三、场景 3:Spring Boot + application.yml(更简洁)

yaml 格式比 properties 更简洁,支持层级结构,Spring Boot 同样原生支持。

1. 配置文件准备

src/main/resources 目录下创建 application.yml

# 服务器配置
server:
  port: 8080

# 数据库配置
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. 代码实现(与 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;

    // 内部静态类(对应层级配置)
    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 与注解中一致(区分大小写)。
  3. yaml 格式错误:yaml 对缩进敏感(必须用空格,不能用 Tab),层级缩进要一致,否则配置无法解析。
  4. 类型转换失败:确保配置值与目标类型匹配(如 app.port 配置为字符串 "abc" 会导致 int 转换失败)。

五、总结

场景推荐方式优势
原生 Java 项目Properties 工具类无依赖、简单易用
Spring Boot 单配置项@Value 注解代码简洁、快速注入
Spring Boot 多配置项@ConfigurationProperties + 配置类结构清晰、支持校验、适配层级配置
偏好简洁格式application.yml + @ConfigurationProperties层级分明、配置文件更简洁

根据项目类型选择合适的方式,Spring Boot 项目优先使用 @ConfigurationProperties(配合 yaml),原生 Java 项目使用 Properties 工具类即可。

以上就是Java从配置文件中获取参数的三种常见场景和完整示例的详细内容,更多关于Java从配置文件中获取参数的资料请关注脚本之家其它相关文章!

相关文章

  • MyBatis-Plus找不到Mapper.xml文件的几种解决方法

    MyBatis-Plus找不到Mapper.xml文件的几种解决方法

    mybatis-plus今天遇到一个问题,就是mybatis 没有读取到mapper.xml 文件,所以下面这篇文章主要给大家介绍了关于MyBatis-Plus找不到Mapper.xml文件的几种解决方法,需要的朋友可以参考下
    2022-06-06
  • java基于swing实现的连连看代码

    java基于swing实现的连连看代码

    这篇文章主要介绍了java基于swing实现的连连看代码,包含了游戏中涉及的事件处理与逻辑功能,需要的朋友可以参考下
    2014-11-11
  • 用JAVA实现单链表,检测字符串是否是回文串

    用JAVA实现单链表,检测字符串是否是回文串

    这篇文章主要介绍了使用JAVA实现单链表,检测字符串是否是回文串,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2020-11-11
  • 一键解决 IntelliJ IDEA中Java/Spring Boot启动失败(“命令行过长")问题

    一键解决 IntelliJ IDEA中Java/Spring Boot启动失败(“命令行过长")问题

    IDEA运行Java程序时出错,提示命令行过长,所以下面这篇文章主要介绍了如何一键解决 IntelliJ IDEA中Java/Spring Boot启动失败(“命令行过长“)问题的相关资料,需要的朋友可以参考下
    2025-11-11
  • 什么是Maven及如何配置国内源实现自动获取jar包的操作

    什么是Maven及如何配置国内源实现自动获取jar包的操作

    本文介绍了Maven的基本概念,包括项目构建、依赖管理、仓库管理以及如何设置国内源,通过Maven,开发者可以自动化管理项目的依赖和构建流程,提高开发效率,感兴趣的朋友跟随小编一起看看吧
    2024-11-11
  • 利用SpringBoot与WebSocket实现实时双向通信功能

    利用SpringBoot与WebSocket实现实时双向通信功能

    随着互联网技术的飞速发展,实时通信技术已经逐渐成为现代Web应用的核心需求,论是在即时消息系统还是物联网(IoT)应用中,WebSocket都提供了一种高效、持久的双向通信方式,本文将深入解析如何利用Spring Boot实现WebSocket通信,需要的朋友可以参考下
    2025-07-07
  • Java实现解析并生成xml原理实例详解

    Java实现解析并生成xml原理实例详解

    这篇文章主要介绍了Java实现解析并生成xml原理实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • 看过就懂的java零拷贝及实现方式详解

    看过就懂的java零拷贝及实现方式详解

    这篇文章主要为大家详细的介绍了什么是零拷贝,传统的IO执行流程,零拷贝相关的知识点回顾,零拷贝实现的几种方式及java提供的零拷贝方式相关内容,有需要的朋友可以借鉴参考下
    2022-01-01
  • Java获得元素属性的注解信息的步骤

    Java获得元素属性的注解信息的步骤

    在Java编程中,注解是一种为代码添加元数据的方式,通过反射机制,我们可以获取元素属性上的注解信息,这个过程对于框架开发和元数据处理非常有用,能够实现更灵活的功能,对java获得元素属性的注解信息相关知识感兴趣的朋友一起看看吧
    2024-09-09
  • java实现的新浪微博分享代码实例

    java实现的新浪微博分享代码实例

    这篇文章主要介绍了java实现的新浪微博分享代码实例,是通过新浪API获得授权,然后接受客户端请求的数据,第三方应用发送请求消息到微博,唤起微博分享界面,非常的实用,有相同需要的小伙伴可以参考下。
    2015-03-03

最新评论