杰瑞科技汇

Java读取property文件路径如何配置?

使用 java.util.Properties 类(最经典、最基础)

这是最传统、最核心的方法,适用于所有 Java 版本,它通过 InputStream 来读取文件。

Java读取property文件路径如何配置?-图1
(图片来源网络,侵删)

核心步骤:

  1. 获取 Properties 对象实例
  2. 使用 ClassLoader 获取资源文件输入流,这种方式可以避免硬编码文件路径,并且能很好地处理打包在 JAR 或 WAR 文件中的资源。
  3. 调用 load(InputStream) 方法将输入流中的内容加载到 Properties 对象中。
  4. 通过 getProperty(String key)getProperty(String key, String defaultValue) 方法获取属性值。
  5. 关闭输入流(推荐使用 try-with-resources 语句自动关闭)。

示例代码

假设你的项目结构如下:

src/
└── main/
    ├── java/
    │   └── com/
    │       └── example/
    │           └── App.java
    └── resources/
        └── config.properties

config.properties 文件内容:

# Database Configuration
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=secret
app.name=My Application
app.version=1.0.0

App.java 代码:

package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App {
    public static void main(String[] args) {
        // 1. 创建 Properties 对象
        Properties props = new Properties();
        // 2. 使用 try-with-resources 自动关闭输入流
        // 使用 ClassLoader 加载资源,路径是相对于 classpath 的
        try (InputStream input = App.class.getClassLoader().getResourceAsStream("config.properties")) {
            // 3. 检查输入流是否为空(文件未找到)
            if (input == null) {
                System.out.println("Sorry, unable to find config.properties");
                return;
            }
            // 4. 加载属性文件
            props.load(input);
            // 5. 获取属性值
            String dbUrl = props.getProperty("db.url");
            String dbUsername = props.getProperty("db.username");
            String dbPassword = props.getProperty("db.password");
            String appName = props.getProperty("app.name");
            // 为属性提供默认值,如果属性不存在则返回默认值
            String appVersion = props.getProperty("app.version", "1.0"); 
            System.out.println("Database URL: " + dbUrl);
            System.out.println("Database Username: " + dbUsername);
            System.out.println("Database Password: " + dbPassword);
            System.out.println("Application Name: " + appName);
            System.out.println("Application Version: " + appVersion);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

关键点说明:

  • App.class.getClassLoader().getResourceAsStream("config.properties"): 这是推荐的方式,它会从 src/main/resources 目录下查找文件,因为该目录在构建后会自动被包含在 classpath 中。
  • 路径问题: 如果你的文件不在 src/main/resources,而是在 src/main/java/com/example/ 下,那么路径需要写成 "com/example/config.properties"
  • try-with-resources: 这是 Java 7 引入的特性,可以确保 InputStream 在使用后自动被关闭,即使发生异常也不会造成资源泄漏。

使用 java.util.ResourceBundle 类(国际化友好)

ResourceBundle 专门用于国际化(i18n)和本地化(l10n),但它也可以非常方便地加载普通的 .properties 文件。

Java读取property文件路径如何配置?-图2
(图片来源网络,侵删)

核心步骤:

  1. 确定资源文件的基名(BaseName),config
  2. ResourceBundle.getBundle(String baseName) 会自动根据 JVM 的默认区域设置查找对应的属性文件。
    • 它会查找 config.properties(默认)、config_zh_CN.properties(简体中文)等。
  3. 通过 getString(String key) 获取属性值。

示例代码

假设 config.properties 文件内容同上。

App.java 代码:

package com.example;
import java.util.ResourceBundle;
public class App {
    public static void main(String[] args) {
        // 1. 指定基名,不需要 .properties 后缀
        // ResourceBundle 会自动从 classpath 中查找
        ResourceBundle rb = ResourceBundle.getBundle("config");
        // 2. 获取属性值
        String dbUrl = rb.getString("db.url");
        String dbUsername = rb.getString("db.username");
        String appName = rb.getString("app.name");
        System.out.println("Application Name: " + appName);
        System.out.println("Database URL: " + dbUrl);
        System.out.println("Database Username: " + dbUsername);
    }
}

关键点说明:

  • 简洁性: 代码非常简洁,不需要手动处理流和异常。
  • 国际化优势: 这是它最大的优点,如果你想为不同语言提供不同的配置,只需创建 config_zh_CN.properties, config_en_US.properties 等文件即可,ResourceBundle 会自动选择合适的文件。
  • 局限性: 它不支持 getProperty(key, defaultValue) 这样的默认值方法,如果键不存在,会抛出 MissingResourceException

使用 Spring Framework 的 @Value 注解(Spring/Spring Boot 环境)

如果你正在使用 Spring 或 Spring Boot 框架,这是最优雅、最推荐的方式,它允许你直接将属性值注入到字段中。

核心步骤:

  1. 确保配置文件在 src/main/resources 目录下(Spring Boot 默认会加载此目录下的 application.propertiesapplication.yml)。
  2. 在类字段上使用 @Value("${key:defaultValue}") 注解。
    • ${key} 是属性的键。
    • defaultValue 是可选的默认值,当属性不存在时使用。

示例代码

config.properties 文件内容同上。

App.java 代码:

package com.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@SpringBootApplication
// @PropertySource 可以指定加载非默认的 properties 文件
@PropertySource("classpath:config.properties")
@Component
public class App {
    // 直接注入属性值
    @Value("${db.url}")
    private String dbUrl;
    @Value("${db.username}")
    private String dbUsername;
    @Value("${app.name:My Default App}") // 提供默认值
    private String appName;
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    // 可以通过 @PostConstruct 或在方法中打印这些值
    public void displayConfig() {
        System.out.println("Application Name: " + appName);
        System.out.println("Database URL: " + dbUrl);
        System.out.println("Database Username: " + dbUsername);
    }
}

注意:在 Spring Boot 中,通常不需要 @PropertySource,因为它会自动加载 application.properties,这里仅为演示如何加载自定义文件。


使用第三方库(如 Apache Commons Configuration)

当配置文件变得复杂(如嵌套结构、列表、数组等)时,标准的 Properties 类就显得力不从心了,这时可以考虑功能更强大的第三方库,如 Apache Commons Configuration。

示例代码(读取嵌套配置)

假设 config.xml 文件内容:

<configuration>
    <database>
        <url>jdbc:mysql://localhost:3306/mydb</url>
        <user>root</user>
        <password>secret</password>
    </database>
    <application>
        <name>My Application</name>
        <servers>
            <server>server1.example.com</server>
            <server>server2.example.com</server>
        </servers>
    </application>
</configuration>

App.java 代码:

import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
public class App {
    public static void main(String[] args) {
        Parameters params = new Parameters();
        FileBasedConfigurationBuilder<XMLConfiguration> builder =
                new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
                        .configure(params.xml().setFileName("config.xml"));
        try {
            XMLConfiguration config = builder.getConfiguration();
            // 使用点号路径访问嵌套属性
            String dbUrl = config.getString("database.url");
            String appName = config.getString("application.name");
            // 获取列表
            String[] servers = config.getStringArray("application.server");
            System.out.println("Database URL: " + dbUrl);
            System.out.println("Application Name: " + appName);
            System.out.println("Servers: ");
            for (String server : servers) {
                System.out.println("  - " + server);
            }
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }
}

总结与选择建议

方法 优点 缺点 适用场景
java.util.Properties 标准、基础、无需依赖,灵活性高 需要手动处理IO和异常,不支持复杂结构 Java SE 项目,或任何需要读取简单属性文件的场景。
java.util.ResourceBundle 简洁、国际化支持好,自动处理IO 不支持默认值,键不存在会抛异常 国际化应用,或需要简单加载属性且不关心IO细节的场景。
Spring @Value 非常优雅、与框架集成好,支持SpEL表达式 强依赖Spring框架 Spring/Spring Boot 项目,推荐作为首选。
第三方库 功能强大,支持XML/YAML/JSON等多种格式,支持复杂嵌套、列表等 引入外部依赖,项目会变大 配置非常复杂,需要从多种来源读取配置,或者已有项目依赖该库。

如何选择?

  1. 如果你在写一个普通的 Java SE 应用(没有用框架):使用 java.util.Properties 是最稳妥、最标准的选择。
  2. 如果你的应用需要国际化:使用 java.util.ResourceBundle
  3. 如果你在使用 Spring 或 Spring Boot:毫不犹豫地使用 @Value 注解,它会让你的代码更干净。
  4. 如果你的配置文件结构非常复杂(包含数组、嵌套对象):考虑引入 Apache Commons Configuration 这样的第三方库。
分享:
扫描分享到社交APP
上一篇
下一篇