王之一羊 發表於 2026-1-9 10:00:54

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

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>引言</li><li>一、场景 1:原生 Java + properties 配置文件(无框架)</li><ul class="second_class_ul"><li>1. 配置文件准备</li><li>2. 代码实现(原生 Properties 类)</li><li>3. 核心说明</li></ul><li>二、场景 2:Spring Boot + application.properties(最常用)</li><ul class="second_class_ul"><li>1. 配置文件准备</li><li>2. 代码实现(3 种方式)</li><ul class="third_class_ul"><li>方式 1:@Value 注解(直接注入,最简单)</li><li>方式 2:Environment 接口(动态获取,适合多环境)</li><li>方式 3:@ConfigurationProperties(绑定配置类,推荐多配置项)</li></ul><li>3. 核心说明</li><ul class="third_class_ul"></ul></ul><li>三、场景 3:Spring Boot + application.yml(更简洁)</li><ul class="second_class_ul"><li>1. 配置文件准备</li><ul class="third_class_ul"></ul><li>2. 代码实现(与 properties 完全兼容)</li><ul class="third_class_ul"></ul><li>3. 使用示例</li><ul class="third_class_ul"></ul></ul><li>四、常见问题排查</li><ul class="second_class_ul"></ul><li>五、总结</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>引言</h2>
<p>在 Java 中从配置文件获取参数是开发中的常见需求,不同配置文件格式(<code>properties</code>、<code>yaml</code>)和框架(原生 Java、Spring Boot)有不同的实现方式。以下是 <strong>最常用的 3 种场景+完整示例</strong>,覆盖原生 Java 和 Spring Boot 项目,直接复用即可。</p>
<p class="maodian"></p><h2>一、场景 1:原生 Java + properties 配置文件(无框架)</h2>
<p><code>properties</code> 是 Java 原生支持的配置文件格式,无需额外依赖,适合简单项目(如纯 Java 工具类、非 Spring 项目)。</p>
<p class="maodian"></p><p class="maodian"></p><p class="maodian"></p><h3>1. 配置文件准备</h3>
<p>在项目 <code>src/main/resources</code> 目录下创建 <code>config.properties</code> 文件:</p>
<div class="jb51code"><pre class="brush:yaml;"># 数据库配置
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
</pre></div>
<p class="maodian"></p><h3>2. 代码实现(原生 Properties 类)</h3>
<p>通过 <code>java.util.Properties</code> 类读取配置文件,核心是加载文件流并解析键值对:</p>
<div class="jb51code"><pre class="brush:java;">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);
    }
}
</pre></div>
<p class="maodian"></p><p class="maodian"></p><h3>3. 核心说明</h3>
<ul><li>配置文件路径:<code>src/main/resources</code> 是类路径(classpath)默认目录,文件会被打包到 Jar 中,通过 <code>ClassLoader.getResourceAsStream()</code> 加载。</li><li>类型转换:原生 <code>Properties</code> 只支持字符串,需手动转换为 <code>int</code>、<code>boolean</code> 等类型(可封装工具方法简化)。</li><li>静态代码块:确保配置文件只加载一次,避免重复 IO 操作。</li></ul>
<p class="maodian"></p><h2>二、场景 2:Spring Boot + application.properties(最常用)</h2>
<p>Spring Boot 项目默认支持 <code>application.properties</code> 配置文件,通过 <code>@Value</code> 注解或 <code>Environment</code> 接口可快速获取参数,无需手动加载文件。</p>
<h3>1. 配置文件准备</h3>
<p>在 <code>src/main/resources</code> 目录下创建 <code>application.properties</code>(Spring Boot 默认配置文件):</p>
<div class="jb51code"><pre class="brush:yaml;"># 服务器配置
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
</pre></div>
<p class="maodian"></p><h3>2. 代码实现(3 种方式)</h3>
<p class="maodian"></p><h4>方式 1:@Value 注解(直接注入,最简单)</h4>
<p>适合在 Bean 中直接注入单个配置项:</p>
<div class="jb51code"><pre class="brush:java;">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;
    }
}
</pre></div>
<p class="maodian"></p><h4>方式 2:Environment 接口(动态获取,适合多环境)</h4>
<p>适合在代码中动态获取配置(如根据条件切换配置项):</p>
<div class="jb51code"><pre class="brush:java;">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);
    }
}
</pre></div>
<p class="maodian"></p><h4>方式 3:@ConfigurationProperties(绑定配置类,推荐多配置项)</h4>
<p>适合配置项较多的场景,将配置绑定到一个实体类,结构更清晰(推荐):</p>
<ol><li>配置文件(同 <code>application.properties</code>);</li><li>配置类:</li></ol>
<div class="jb51code"><pre class="brush:java;">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;
    }
}
</pre></div>
<ol start="3"><li>使用配置类:</li></ol>
<div class="jb51code"><pre class="brush:java;">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();
    }
}
</pre></div>
<h3>3. 核心说明</h3>
<ul><li>配置文件优先级:Spring Boot 会加载 <code>application.properties</code>、<code>application-dev.properties</code>(开发环境)等,通过 <code>spring.profiles.active=dev</code> 切换环境。</li><li>类型转换:Spring 自动将配置值转换为 <code>int</code>、<code>boolean</code> 等类型,无需手动处理。</li><li><code>@ConfigurationProperties</code> 优势:支持配置校验(如 <code>@NotNull</code>、<code>@Min</code>)、自动绑定下划线/短横线命名(如 <code>app.max-file-size</code> 对应 <code>maxFileSize</code>)。</li></ul>
<p class="maodian"></p><h2>三、场景 3:Spring Boot + application.yml(更简洁)</h2>
<p><code>yaml</code> 格式比 <code>properties</code> 更简洁,支持层级结构,Spring Boot 同样原生支持。</p>
<h3>1. 配置文件准备</h3>
<p>在 <code>src/main/resources</code> 目录下创建 <code>application.yml</code>:</p>
<div class="jb51code"><pre class="brush:yaml;"># 服务器配置
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
</pre></div>
<p class="maodian"></p><h3>2. 代码实现(与 properties 完全兼容)</h3>
<p><code>yaml</code> 只是配置文件格式不同,Java 代码获取方式与 Spring Boot + properties 完全一致,无需修改:</p>
<div class="jb51code"><pre class="brush:java;">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;
    }
}
</pre></div>
<p class="maodian"></p><h3>3. 使用示例</h3>
<div class="jb51code"><pre class="brush:java;">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;
    }
}
</pre></div>
<p class="maodian"></p><h2>四、常见问题排查</h2>
<ol><li><strong>配置文件找不到</strong>:确保配置文件在 <code>src/main/resources</code> 目录下(Maven 项目默认资源目录),打包后检查 Jar 包中是否包含该文件。</li><li><strong>@Value 注入为 null</strong>:确保类被 Spring 管理(添加 <code>@Component</code> 等注解),且配置项 key 与注解中一致(区分大小写)。</li><li><strong>yaml 格式错误</strong>:yaml 对缩进敏感(必须用空格,不能用 Tab),层级缩进要一致,否则配置无法解析。</li><li><strong>类型转换失败</strong>:确保配置值与目标类型匹配(如 <code>app.port</code> 配置为字符串 <code>&quot;abc&quot;</code> 会导致 <code>int</code> 转换失败)。</li></ol>
<p class="maodian"></p><h2>五、总结</h2>
<table><thead><tr><th>场景</th><th>推荐方式</th><th>优势</th></tr></thead><tbody><tr><td>原生 Java 项目</td><td>Properties 工具类</td><td>无依赖、简单易用</td></tr><tr><td>Spring Boot 单配置项</td><td>@Value 注解</td><td>代码简洁、快速注入</td></tr><tr><td>Spring Boot 多配置项</td><td>@ConfigurationProperties + 配置类</td><td>结构清晰、支持校验、适配层级配置</td></tr><tr><td>偏好简洁格式</td><td>application.yml + @ConfigurationProperties</td><td>层级分明、配置文件更简洁</td></tr></tbody></table>
<p>根据项目类型选择合适的方式,Spring Boot 项目优先使用 <code>@ConfigurationProperties</code>(配合 yaml),原生 Java 项目使用 Properties 工具类即可。</p>
<p>以上就是Java从配置文件中获取参数的三种常见场景和完整示例的详细内容,更多关于Java从配置文件中获取参数的资料请关注琼殿技术社区其它相关文章!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>Java获取请求头、参数、路径方式</li><li>java反射获取方法参数名的几种方式总结</li><li>Java通过反射获取方法参数名的方式小结</li><li>Java获取启动参数方式</li><li>Java如何获取HttpServletRequest请求参数</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: Java从配置文件中获取参数的三种常见场景和完整示例