Java如何从配置文件中获取参数(举例)

在 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 工具类即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值