什么是 .properties 文件?
它是一种简单的文本文件,用于存储配置信息,例如数据库连接信息、API密钥、系统参数等,文件中的内容是键值对格式。

config.properties 示例文件:
# 数据库配置 db.url=jdbc:mysql://localhost:3306/mydatabase db.username=root db.password=secret db.pool.size=10 # 应用配置 app.name=My Cool Application app.version=1.0.0
使用 java.util.Properties 类 (最基础、最常用)
这是 Java 标准库提供的方法,适用于读取位于类路径(Classpath)下的资源文件,这是最灵活和推荐的方式。
核心步骤:
- 创建
Properties对象:Properties props = new Properties(); - 获取输入流:使用
ClassLoader.getResourceAsStream()来读取类路径下的文件。强烈推荐使用这种方式,因为它可以很好地处理打包成 JAR 或 WAR 文件后的路径问题。 - 加载文件:调用
props.load(inputStream)方法。 - 获取属性值:使用
props.getProperty("key")方法。 - 关闭流:使用
try-with-resources语句自动关闭输入流。
完整代码示例:
假设你的 config.properties 文件位于 src/main/resources 目录下(这是 Maven/Gradle 项目的标准结构)。
import java.io.InputStream;
import java.util.Properties;
public class PropertyReader {
public static void main(String[] args) {
// 1. 创建 Properties 对象
Properties props = new Properties();
// 使用 try-with-resources 确保 InputStream 自动关闭
try (InputStream input = PropertyReader.class.getClassLoader().getResourceAsStream("config.properties")) {
// 2. 检查文件是否存在
if (input == null) {
System.out.println("Sorry, unable to find config.properties");
return;
}
// 3. 加载属性文件
props.load(input);
// 4. 获取属性值
String dbUrl = props.getProperty("db.url");
String dbUsername = props.getProperty("db.username");
String dbPassword = props.getProperty("db.password");
int poolSize = Integer.parseInt(props.getProperty("db.pool.size")); // 转换为基本类型
String appName = props.getProperty("app.name");
String appVersion = props.getProperty("app.version");
// 打印读取到的配置
System.out.println("应用名称: " + appName);
System.out.println("应用版本: " + appVersion);
System.out.println("--------------------");
System.out.println("数据库URL: " + dbUrl);
System.out.println("数据库用户名: " + dbUsername);
System.out.println("数据库密码: " + dbPassword);
System.out.println("连接池大小: " + poolSize);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
关键点说明:

PropertyReader.class.getClassLoader().getResourceAsStream("config.properties"):这是获取类路径下资源的标准方式。getClassLoader()会在src/main/resources(或 Maven/Gradle 对应的输出目录) 中查找文件。props.getProperty("key"):如果键不存在,会返回null。props.getProperty("key", "defaultValue"):如果键不存在,会返回指定的默认值,这可以避免NullPointerException。- 类型转换:
Properties类只存储String类型的值,如果需要其他类型(如int,long,boolean),需要手动进行转换,如Integer.parseInt()。
使用 ResourceBundle 类 (适合国际化)
ResourceBundle 主要用于国际化(i18n),但它也可以非常方便地加载 .properties 文件,它不会抛出 IOException,因为它在初始化时就会加载资源。
核心步骤:
- 创建
ResourceBundle对象:ResourceBundle bundle = ResourceBundle.getBundle("baseName", locale);baseName是文件名,但不包含.properties后缀和语言国家代码。- 文件必须位于类路径下。
- 获取属性值:使用
bundle.getString("key")方法。
完整代码示例:
假设文件名是 messages.properties,位于 src/main/resources。
messages.properties
greeting=Hello farewell=Goodbye
MessagesLoader.java

import java.util.ResourceBundle;
public class MessagesLoader {
public static void main(String[] args) {
// baseName 是 "messages",会自动寻找 messages.properties
ResourceBundle messages = ResourceBundle.getBundle("messages");
// 获取属性值
String greeting = messages.getString("greeting");
String farewell = messages.getString("farewell");
System.out.println(greeting + ", World!"); // 输出: Hello, World!
System.out.println(farewell); // 输出: Goodbye
}
}
特点:
- 简单:代码非常简洁。
- 国际化:可以轻松加载不同语言的文件,如
messages_en_US.properties(美式英语),messages_zh_CN.properties(简体中文)。 - 限制:
- 只能处理
String类型的值。 - 文件名必须遵循严格的命名规范(
baseName_locale.properties)。 - 不适合存储包含大量配置或非字符串数据的文件。
- 只能处理
使用 Spring Boot 的 @ConfigurationProperties (企业级应用首选)
如果你正在使用 Spring Boot,这是最推荐、最强大的方式,它可以将整个 .properties 或 application.yml 文件自动绑定到一个类型安全的 Java 对象(POJO)中。
核心步骤:
- 创建一个配置类:使用
@ConfigurationProperties注解标记该类,并指定前缀。 - 创建对应的字段:类中的字段名会自动与配置文件中的键(去掉前缀后)匹配。
- 在主应用类或配置类上添加
@EnableConfigurationProperties。 - 注入并使用:将配置类注入到任何需要它的 Spring Bean 中。
完整代码示例:
config.properties 文件
# application.properties myapp.db.url=jdbc:mysql://localhost:3306/mydb myapp.db.username=admin myapp.db.password=123456 myapp.db.pool-size=20 myapp.name=Spring Boot App myapp.version=2.0.0
创建配置类 AppProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component // 声明为 Spring Bean
@ConfigurationProperties(prefix = "myapp") // 绑定以 myapp. 为前缀的属性
public class AppProperties {
private DbSettings db;
private String name;
private String version;
// 内部类,用于组织配置
public static class DbSettings {
private String url;
private String username;
private String password;
private int poolSize; // Spring Boot 会自动转换类型
// Getters and Setters (必须提供!)
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public int getPoolSize() { return poolSize; }
public void setPoolSize(int poolSize) { this.poolSize = poolSize; }
}
// Getters and Setters for AppProperties (必须提供!)
public DbSettings getDb() { return db; }
public void setDb(DbSettings db) { this.db = db; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
}
在主应用类中启用
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class) // 显式启用
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
在其他服务中使用
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyService {
private final AppProperties appProperties;
// 通过构造器注入,推荐方式
@Autowired
public MyService(AppProperties appProperties) {
this.appProperties = appProperties;
}
public void printConfig() {
System.out.println("应用名称: " + appProperties.getName());
System.out.println("数据库URL: " + appProperties.getDb().getUrl());
// ... 其他配置
}
}
优点:
- 类型安全:IDE 可以提供自动补全,编译时检查类型错误。
- 结构化:配置被组织在对象中,非常清晰。
- 松耦合:业务代码不直接依赖
Properties类,而是依赖一个 POJO。 - 支持复杂类型:可以轻松集成如
Duration,DataSize等 Spring Boot 特殊类型。
总结与选择
| 方法 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
java.util.Properties |
通用、标准,适用于任何 Java 项目(SE/EE)。 | 灵活,可处理任何路径,是 Java 基础知识。 | 需要手动处理类型转换和异常,代码稍显冗长。 |
ResourceBundle |
国际化,或需要简单、只读的字符串配置。 | 代码简洁,自动处理不同语言环境。 | 只支持 String,文件名受限,不适合复杂配置。 |
@ConfigurationProperties |
Spring Boot 应用,推荐用于企业级项目。 | 类型安全,结构化,与 Spring 生态完美集成。 | 依赖 Spring Boot 框架。 |
如何选择?
- 如果你在学习 Java 基础或在不使用框架的项目中:使用
java.util.Properties,这是你必须掌握的核心技能。 - 如果你在做一个多语言应用:使用
ResourceBundle。 - 如果你在开发 Spring Boot 应用:毫不犹豫地使用
@ConfigurationProperties,这是最佳实践,能让你的代码更健壮、更易于维护。
