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从配置文件中获取参数的资料请关注脚本之家其它相关文章!

相关文章

  • Java编程synchronized与lock的区别【推荐】

    Java编程synchronized与lock的区别【推荐】

    互联网信息泛滥环境下少有的良心之作!如果您想对Java编程synchronized与lock的区别有所了解,这篇文章绝对值得!分享给大家,供需要的朋友参考。不说了,我先学习去了。
    2017-10-10
  • SpringBoot整合Redis实现访问量统计的示例代码

    SpringBoot整合Redis实现访问量统计的示例代码

    本文主要介绍了SpringBoot整合Redis实现访问量统计的示例代码,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • spring boot启动加载数据原理分析

    spring boot启动加载数据原理分析

    实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。这时spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。下面给大家详细介绍下,需要的的朋友参考下吧
    2017-04-04
  • MyBatis批量操作XML的完整实现方案

    MyBatis批量操作XML的完整实现方案

    本文介绍了MyBatis通过XML映射文件实现批量插入、更新和删除的完整方案,包括单条SQL批量插入、批量插入并返回主键、批量更新、批量删除以及动态批量操作,最后,分享了最佳实践建议,需要的朋友可以参考下
    2025-12-12
  • Spring 零基础入门WebFlux框架体系

    Spring 零基础入门WebFlux框架体系

    Spring5发布有两年了,随Spring5一起发布了一个和Spring WebMvc同级的Spring WebFlux。这是一个支持反应式编程模型的新框架体系。反应式模型区别于传统的MVC最大的不同是异步的、事件驱动的、非阻塞的,这使得应用程序的并发性能会大大提高,单位时间能够处理更多的请求
    2022-07-07
  • springboot+thymeleaf+layui的实现示例

    springboot+thymeleaf+layui的实现示例

    本文主要介绍了springboot+thymeleaf+layui的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-12-12
  • Java优秀类库Hutool使用示例

    Java优秀类库Hutool使用示例

    Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,涵盖了Java开发开发中的方方面面,使用Hutool可节省开发人员对项目中公用类和公用工具方法的封装时间,使开发专注于业务,同时可以最大限度的避免封装不完善带来的bug
    2023-02-02
  • Maven与Gradle的区别对比分析

    Maven与Gradle的区别对比分析

    这篇文章给大家给大家介绍了Maven与Gradle的区别对比分析,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2026-05-05
  • java list与数组之间的转换详细解析

    java list与数组之间的转换详细解析

    以下是对java中list与数组之间的转换进行了详细的分析介绍,需要的朋友可以过来参考下
    2013-09-09
  • IDEA反编译jar,查看源码方式

    IDEA反编译jar,查看源码方式

    该篇文章总结了查看Java本地jar包注释的几种方法,包括使用快捷键CTRL+q和在设置中设置自动浮现注释
    2024-11-11

最新评论